Set focus in input on clicking div

Viewed 1758

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

3 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>
  );
}

you can set id to input and use input to focus on input example

import React from "react";
import "./styles.css";

export default function App() {
return (
<div className="App">
  <div
    className='inputCon'
   onClick={()=>{
    const input = document.getElementById("input");
    input.focus()
  }}>
      <input 
      placeholder="click on green area"
      id="input"
       />
  </div>
</div>
  );
}

You don't necessarily need a ref for that. The following code hooks up directly into the click event, find the closest input child, and focus on it. Click anywhere in the orange zone to focus on the input:

const MyComponent = () => {
  const onClick = evt => {
    evt.target.querySelector('input').focus();
  };
  return (<div onClick={onClick}><input/></div>);
}

ReactDOM.render((<MyComponent/>), document.body);
div {
  padding: 1em;
  background-color: coral;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Related