ReactJS How to focus input element on render| useRef and useEffect example
This post talks about how to set focus on the input element in Form validation in Reactjs.
Adding Input focus to the input elements on UI forms makes validation easy and controls input elements via the 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 are also called Class components
Using this 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 an initial value, return a mutable ref to DOM elements useEffect hook in react equivalent to ComonentDidMount called once component is mounted. set focus to the input element in use effect function Added ref to input attribute.
Example Functional component to set focus control on the 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