Skip to content Skip to sidebar Skip to footer

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()

Solution 1:

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;

functionFoo() {
  const txt1 = useRef(null);

  useEffect(() => {
    txt1.current.focus();
  }, []);

  return<inputtype="text"ref={txt1} />;
}

ReactDOM.render(<Foo />, document.getElementById("root"));
<scriptsrc="https://unpkg.com/react@16.7.0-alpha.0/umd/react.production.min.js"></script><scriptsrc="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.production.min.js"></script><divid="root"></div>

Solution 2:

According to official docs: https://reactjs.org/docs/hooks-reference.html#useref you can use useRef.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

A common use case is to access a child imperatively:

functionTextInputWithFocusButton() {
  const inputEl = useRef(null);
  constonButtonClick = () => {
    // `current` points to the mounted text input element
    inputEl.current.focus();
  };
  return (
    <><inputref={inputEl}type="text" /><buttononClick={onButtonClick}>Focus the input</button></>
  );
}

Essentially, useRef is like a “box” that can hold a mutable value in its .current property.

You might be familiar with refs primarily as a way to access the DOM. If you pass a ref object to React with <div ref={myRef} />, React will set its .current property to the corresponding DOM node whenever that node changes.

However, useRef() is useful for more than the ref attribute. It’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.

This works because useRef() creates a plain JavaScript object. The only difference between useRef() and creating a {current: ...} object yourself is that useRef will give you the same ref object on every render.

Keep in mind that useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.

Post a Comment for "React: Set Focus On Componentdidmount, How To Do It With Hooks?"