In React, with classes I can set the focus to an input when the component loads, something like this:
class Foo extends React.Component {
txt1 = null;
componentDidMount() {
this.txt1.focus();
}
render() {
return (
<input type="text"
ref={e => this.txt1 = e}/>
);
}
}
I'm trying to rewrite this component using the new hooks proposal.
I suppose I should use useEffect
instead of componentDidMount
, but how can I rewrite the focus logic?
If you add React to an existing application and render a component into a detached element, React will call focus() before the browser is ready, and the input will not be focused when it gets added to the DOM. So, instead of depending on React to call focus() on the input, we are going to do it ourselves.
To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook. Then we call focus on the current value of the ref to focus on the input. to call useRef to create a ref and assign it to inputReference . Then we call inputReference.
componentDidMount() is a hook that gets invoked right after a React component has been mounted aka after the first render() lifecycle.
The equivalent of componentDidMount in hooks is the useEffect function. Functions passed to useEffect are executed on every component rendering—unless you pass a second argument to it.
You can use the useRef
hook to create a ref, and then focus it in a useEffect
hook with an empty array as second argument to make sure it is only run after the initial render.
const { useRef, useEffect } = React;
function Foo() {
const txt1 = useRef(null);
useEffect(() => {
txt1.current.focus();
}, []);
return <input type="text" ref={txt1} />;
}
ReactDOM.render(<Foo />, 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>
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