reactjsnext.js15

How to keep textbox (HTML input) above keyboard in mobile in ReactJS?


I am trying to clone WhatsApp's biggest issue in UI is my aligning my textbox above keyboard in mobile please help!

This is how I tried to implement it, but it's not great—it's buggy and not smooth

<div ref={chatPageDiv} style={{ height: "100svh"}} className="top-0 z-10">
      
    <div ref={chatBox}
         style={{ 
                height: windowHeight ? windowHeight - 150 - keyBoardHeight : "80svh" 
            }} 
         className="overflow-scroll ">
    </div>
    <ChatpageInput setKeyBoardHeight={setKeyBoardHeight}  />
    {keyBoardHeight > 0 && <EmoteKeyBoard keyBoardHeight= 
     {keyBoardHeight} />}

</div>

Solution

  • This is the most common pattern:

    const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
      e.target.scrollIntoView({ behavior: 'smooth', block: 'center' });
    };
    

    And this you use the onFocus function

    <input type="text" onFocus={handleFocus} />