Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on <div> to focus <input> (React) [closed]

I know how to do this with jquery. But I am stuck with React: How would I focus an input field, whenever the user clicks on a div?

like image 683
George Welder Avatar asked May 05 '17 12:05

George Welder


People also ask

How do you autofocus a div in React?

Autofocusing using React useRef() and useEffect() Hooks We can also get the same functionality with the useRef() and useEffect() React Hooks. Here is the same form using these Hooks: import React, { useRef, useEffect } from "react"; const Form = () => { const emailInput = useRef(null); useEffect(() => { if (emailInput.

How do you set focus on input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

Why does the input field lose focus after typing a character React?

it is because you are rendering the form in a function inside render(). Every time your state/prop change, the function returns a new form. it caused you to lose focus.


2 Answers

You need to have an onClick event on the div and the call the focus() function on the input element that you can access by refs in react

class App extends React.Component {
  
  render() {
    return (
      <div>
          <div onClick={() => {this.myInp.focus()}}>Focus Input</div>
          <input type="text" ref={(ip) => this.myInp = ip} />
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

In the above snippet ref={(ip) => this.myInp = ip} is a callback approach of declaring refs which is recommended by react-docs

like image 94
Shubham Khatri Avatar answered Oct 24 '22 03:10

Shubham Khatri


Check this https://facebook.github.io/react/docs/refs-and-the-dom.html

Via ref you can anything jquery-like.

like image 3
Yozi Avatar answered Oct 24 '22 02:10

Yozi