Welcome to this comprehensive guide on using useRef for DOM manipulation in React JS! In this tutorial, we'll walk you through the basics and advanced examples of working with useRef to interact with the DOM in a clean, practical, and educational manner.
useRef is a built-in React hook that helps you access the DOM or create a mutable value in functional components. It returns a mutable ref object that persists for the entire lifecycle of the component.
You might use useRef for:
Let's create a simple component that renders a heading with a ref:
import React, { useRef } from 'react';
function RefExample() {
const headingRef = useRef(null);
const handleClick = () => {
headingRef.current.style.color = 'red';
};
return (
<div>
<h1 ref={headingRef}>Hello, World!</h1>
<button onClick={handleClick}>Change color</button>
</div>
);
}
export default RefExample;In the example above, useRef(null) creates a new ref object and initializes it to null. The ref is then assigned to the h1 element using the ref attribute. The handleClick function changes the color of the h1 element when the button is clicked.
š Note: Always initialize the ref to null to avoid warnings.
You can pass refs between components to access DOM nodes in the child component from the parent:
import React, { useRef, useEffect } from 'react';
function Parent() {
const inputRef = useRef(null);
useEffect(() => {
console.log(inputRef.current.value);
}, [inputRef]);
return <Child refInput={inputRef} />;
}
function Child({ refInput }) {
return <input ref={refInput} type="text" />;
}
export default Parent;In the example above, the parent component creates a ref using useRef(null). The ref is passed to the child component as a prop called refInput. The child component sets the ref on the input element. The parent component logs the input value when it updates using the useEffect hook.
What does useRef return?
Let's create a custom text input component that uses useRef to manage form state:
import React, { useRef, useState } from 'react';
function TextInput({ label }) {
const inputRef = useRef(null);
const [value, setValue] = useState('');
const handleInputChange = (event) => {
setValue(event.target.value);
};
const handleFocus = () => {
inputRef.current.select();
};
return (
<div>
<label>{label}</label>
<input
ref={inputRef}
value={value}
onChange={handleInputChange}
onFocus={handleFocus}
/>
</div>
);
}
export default TextInput;In the example above, useRef(null) creates a new ref object for the input element. The useState hook manages the input value. The handleInputChange function updates the input value. The handleFocus function selects the input content when it receives focus.
In this tutorial, you've learned about using useRef for DOM manipulation in React JS. You've seen how to create refs, access DOM nodes, and pass refs between components. Practice using these concepts to build interactive, real-world components!
Stay tuned for more in-depth lessons on React JS at CodeYourCraft! šÆš