Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus in input on clicking div

Tags:

focus

reactjs

I have the following HTML inside function component

<div>
   <input />
<div>
<div>
   <input />
<div>
<div>
   <input />
<div>

I am not finding any easy way to do this...

I have gone some article saying to store input ref, but here I have confusion about how to store inputref using id or something...

I am totally lost so unable to proceed

Please help

Thanks

like image 967
Md. Parvez Alam Avatar asked Sep 01 '25 04:09

Md. Parvez Alam


1 Answers

The use of the useRef-Hook is explained in great detail here.

But basically you create a ref and in your onClick you add the call .focus() on it like this:

function CustomTextInput(props) {
  // textInput must be declared here so the ref can refer to it
  const textInput = useRef(null);
  
  function handleClick() {
    textInput.current.focus();
  }

  return (
    <div>
      <input
        type="text"
        ref={textInput} />
      <input
        type="button"
        value="Focus the text input"
        onClick={handleClick}
      />
    </div>
  );
}
like image 57
Moritz W Avatar answered Sep 02 '25 18:09

Moritz W