Skip to content

How to set focus on element after rendering with React?

When building web applications with React, you may want to set focus on a particular element after it has been rendered. This can be useful for improving the accessibility of your application, as well as enhancing the user experience. In this article, we’ll explore how to set focus on an element after rendering with React.

Add Refs to the Elements

To set focus on an element, we first need to add a ref to the element in the JSX code. Refs provide a way to access DOM elements directly from the component code.

Here’s an example:

<input type="text" ref={input => input && input.focus()} />

This code adds a ref to an input element and sets focus on it after rendering.

Set Focus in componentDidMount()

Once we’ve added a ref to the element, we can set focus on it in the componentDidMount() lifecycle method. This method is called after the component has been rendered to the DOM.

Here’s an example:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
      </div>
    );
  }
}

This code creates a component that adds a ref to an input element and sets focus on it in the componentDidMount() method.

Set Focus in useEffect()

If you’re using functional components, you can use the useEffect() hook to set focus on an element after rendering.

Here’s an example:

function MyComponent() {
  const myRef = useRef(null);

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

  return (
    <div>
      <input type="text" ref={myRef} />
    </div>
  );
}

This code creates a functional component that adds a ref to an input element and sets focus on it using the useEffect() hook.

See also  Resizing images in React

That’s it! Setting focus on an element after rendering can be a useful technique for improving the accessibility and user experience of your React application. By using refs and the componentDidMount() lifecycle method or the useEffect() hook, you can easily set focus on any element after it has been rendered. Remember to test your application with screen readers and other accessibility tools to ensure that it works well for all users.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.