Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: set focus on componentDidMount, how to do it with hooks?

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?

like image 533
rodrigocfd Avatar asked Nov 07 '18 11:11

rodrigocfd


People also ask

How do you set focus on React Hooks?

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.

How will you focus on the input field when the page is loaded React?

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.

Is componentDidMount a hook?

componentDidMount() is a hook that gets invoked right after a React component has been mounted aka after the first render() lifecycle.

What is the hook equivalent of componentDidMount?

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.


1 Answers

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>
like image 76
Tholle Avatar answered Oct 11 '22 12:10

Tholle