How to access the dom nodes in React using refs
In this tutorial, we will learn about how to use the ref attribute to access the dom nodes in React.
Have you seen if you open Google.com the search box is focused automatically?. The same thing we created below using ref attribute.
We can create the ref by using the React.createRef() method.
class Search extends React.Component {
inputText = React.createRef();
componentDidMount() {
this.inputText.current.focus(); }
render() {
return (
<div>
<input type="text" ref={this.inputText} placeholder="search" /> </div>
);
}
}In the above code, we first invoked the React.createRef() method and passed it to the input element ref atribute.
In componentDidMount() lifecycle method we accessed that input element by using current property.
React assings the dom element to the current property whenever the component mounts, and assigns back to null when component unmounts.
We can also use ref’s inside the functional components like this.
import React from "react";
function SmallComponent() {
const inputText = React.createRef();
function handleFocus() {
inputText.current.focus(); }
return (
<div>
<input ref={inputText} type="text" /> <button onClick={handleFocus}>Focus</button> </div>
);
}Callback refs
There is also another way to use refs by using callback functions where react passes the dom element as an argument to the callback function.
Here is an example:
class Search extends React.Component {
componentDidMount() {
this.inputText.focus();
}
render() {
return (
<div>
<input
type="text"
ref={(node) => (this.inputText = node)} placeholder="search"
/>
</div>
);
}
}React invokes the callback function by passing a dom element when the component mounts and
passes null when component unmounts.
Other example Login form
class Login extends React.Component {
state = {
username: null,
password: null,
};
handleSubmit = (e) => {
e.preventDefault();
this.setState({
username: this.refusername.value,
password: this.refpassword.value,
});
};
render() {
return (
<form>
<input type="text" ref={(name) => (this.refusername = name)} />
<input type="password" ref={(pass) => (this.refpassword = pass)} />
<button onClick={this.handleSubmit}>Login</button>
</form>
);
}
}Note: ref updates happen before
componentDidMount()andcomponentDidUpdate()life cycle methods.


