How to use React useRef hook with examples
In this tutorial, we are going to learn about how to access the dom nodes in react by using useRef hook.
React hooks are JavaScript functions which helps us to use the missing react features in functional components.
useRef hook
In react useRef
hook helps us to access the dom nodes or html elements, so that we can interact with that dom element like accessing the input
element value or focussing the input
element.
example:
import React,{useRef} from 'react';
function TextInput(){
//creating the ref by passing initial value null
const nameRef = useRef(null);
function handleFocus(){
//current property is pointing to the input element
//when a component is mounts to dom
nameRef.current.focus() }
return(
<div>
<input ref={nameRef} placeholder="name" /> <button onClick={handleFocus}>Focus</button>
</div>
)
}
In the above example, we have imported useRef
hook from the ‘react’ then we invoked the useRef
hook by passing the initial value null
.
In input
element we defined ref attribute by passing the nameRef
so that we can access that input element by using nameRef.current
property.