ReactJS How to focus input element on render| useRef and useEffect example


This post talks about how to set focus on input element in Form validation in Reactjs

Adding Input focus to the input elements on UI forms makes validation easy and control input elements via keyboard tab.

focus input element using ref in react class components

ref and createRef in ReactJS provides an access specific DOM element in stateful components. These also called as Class components

Using this, It provides focus control to input elements.

  • Create input element, add ref directive
  • Initialize the input ref in Constructor using React.createRef()
  • ComponentDidMount is a callback called after component is mounted.
  • Access the element using this.inputRef.current, call focus() method

Complete component code:

import React, { Component } from 'react';

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

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

    render() {
        return (
            <div>
                <label>Enter Name</label>
                <input type="text" ref={this.inputRef} />

            </div>
        );
    }
}

export default InputFocusComponent;

focus input element using ref in react class components

useEffect, useRef are hooks in reactjs to access DOM elements in functional components. These also called stateless components.

useRef hook with initial value, return mutable ref to DOM elements useEffect hook in react equivalent to ComonentDidMount called once component is mounted. set focus to input element in useEffect function Added ref to input attribute.

Example Functional component to set focus control on input element in react

import React, { useEffect, useRef } from 'react';

const InputFocusUseHook = () => {
    const inputRef = useRef(null);
    useEffect(() => inputRef.current && inputRef.current.focus());

    return (
        <div>
            <label>Enter Name</label>
            <input type="text" ref={inputRef} />

        </div>
    );
};

export default InputFocusUseHook;

Conclusion

This post covers setting focus on input element in ReactJS

  • ref and CreateRef accessing DOM
  • useRef and useEffect hooks
THE BEST NEWSLETTER ANYWHERE
Join 90,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts