Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useref not adding focus state to field

I've been trying to find a solution for this, where I'd like to add the focus state to my input field. But it doesn't seem to be working:

const textareaRef = useRef<HTMLInputElement>(null);
...

const handleClick = () => {
        if (textareaRef.current) {
            alert('Field clicked');
            textareaRef.current.focus();
            textareaRef.current.click();
        }
    };

...

<input
     ref={textareaRef}
     onClick={handleClick}
     onFocus={(e) => e.persist()}
     spellCheck="false"
/>

This doesn't work, and the main reason is to show the mobile keyboard. See video here of it not working https://share.getcloudapp.com/jkuYLqO5 and here without alert https://share.getcloudapp.com/wbuKwrLE

like image 718
designtocode Avatar asked Feb 23 '26 22:02

designtocode


1 Answers

I cannot reproduce the bug on desktop browser. What browser is it in the screen recording?

function App() {
  const textareaRef = React.useRef();
  const handleClick = () => {
    if (textareaRef.current) {
        console.log('Field clicked');
        textareaRef.current.focus();
    }
  };

  return (
    <div>
      <div onClick={handleClick}>click me to focus input</div>
      <input
       ref={textareaRef}
       onFocus={(e) => e.persist()}
      />
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 133
hackape Avatar answered Feb 25 '26 12:02

hackape