designtocode
designtocode

Reputation: 2245

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

Upvotes: 4

Views: 8846

Answers (2)

hackape
hackape

Reputation: 19987

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>

Upvotes: 1

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8118

You can do this in useEffect() Hook. Below component mocks your scenario. As the component loads, I make focus() appear on input.

import React, { useEffect, useRef } from 'react';


const UseRefBasics = () => {
  const refContainer = useRef(null);

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(refContainer.current.value);
  };
  useEffect(() => {
    console.log(refContainer.current);
    refContainer.current.focus();
  });

  return (
    <>
      <form className='form' onSubmit={handleSubmit}>
        <div>
          <input type='text' ref={refContainer} />
        </div>
        <button type='submit'>submit</button>
      </form>
    </>
  );
};

export default UseRefBasics;

This is a general scenario that I have given. You may use useEffect() and get your focus when the state updates by providing another argument to useEffect(()=>{},[state1]) or in whatever way you need it.

Upvotes: 0

Related Questions