Logo

What's the react way of setting focus on a particular text field after the component is rendered?

Setting focus on a specific text field in React is often needed for improved accessibility and user experience. The key is to use Refs (references) to directly access and manipulate DOM elements after they’ve been rendered. Below, we’ll explore how to do this in both function components and class components.

1. Using useRef in Function Components

In modern React (with hooks), the most straightforward way is to use the useRef hook alongside the useEffect hook:

import React, { useRef, useEffect } from 'react'; function TextInputWithFocus() { const inputRef = useRef(null); useEffect(() => { // Focus the input element once the component mounts inputRef.current.focus(); }, []); return ( <div> <input type="text" ref={inputRef} placeholder="I'll be focused on render" /> </div> ); } export default TextInputWithFocus;

How It Works

  • useRef(null) initializes a ref object whose .current property will hold the DOM node reference.
  • useEffect runs after the component is mounted, ensuring we only call .focus() when the element is present in the DOM.

2. Using createRef in Class Components

If you’re working with class-based components, you can still focus an element by creating a ref in the constructor and calling .focus() in the componentDidMount lifecycle:

class TextInputWithFocus extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } componentDidMount() { this.inputRef.current.focus(); } render() { return ( <div> <input type="text" ref={this.inputRef} placeholder="I'll be focused on render" /> </div> ); } } export default TextInputWithFocus;

3. Practical Tips and Best Practices

  1. Conditional Rendering
    • If the input is rendered conditionally (e.g., after an API call), ensure the focus logic runs only when the element is actually on the page. You might need checks or effect dependencies to avoid errors.
  2. Accessibility
    • Setting initial focus can be great for user convenience, but make sure it aligns with accessibility guidelines (e.g., focusing forms, error fields, or modals).
  3. Avoid Overusing Direct DOM Access
    • While refs are handy, don’t use them for state management or as your primary form of data flow. Stick to the “React way” (props and state) for data management, and refs for DOM manipulation only.

Further Resources to Level Up Your React & JavaScript

If you want to master not just these details but also broader JavaScript and coding interview skills, consider these resources from DesignGurus.io:

For hands-on practice and feedback, try the Coding Mock Interviews offered by DesignGurus.io, where you’ll get personalized insights from ex-FAANG engineers.

Conclusion

To focus on a text field right after a React component renders, use refs in either function components (useRef) or class components (createRef). Place your focus logic in useEffect (function components) or componentDidMount (class components) so the DOM element is ready. Done correctly, this approach yields a seamless user experience and aligns well with React’s best practices. Happy coding!

CONTRIBUTOR
TechGrind