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?
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.
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.
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.
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
Check this https://facebook.github.io/react/docs/refs-and-the-dom.html
Via ref
you can anything jquery-like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With