The useRef hook in React is a way to access the properties of a DOM element in a functional component. It allows you to create a mutable object that persists across re-renders of the component.
Imagine that you are a painter and you are creating a new painting. You have a canvas and a paintbrush, and you want to keep track of the current color of the paint and the position of the paintbrush on the canvas. To do this, you can use the useRef hook like a palette and a paint tray.
Here is an example of how you might use the useRef hook to access the properties of a DOM element in a functional component:
import { useRef } from "react";
function Painting() {
const canvasRef = useRef(null);
const paintbrushRef = useRef(null);
function handlePaintbrushMove(event) {
const { x, y } = event.target.getBoundingClientRect();
paintbrushRef.current.style.top = y + "px";
paintbrushRef.current.style.left = x + "px";
}
function handleColorChange(event) {
paintbrushRef.current.style.backgroundColor = event.target.value;
}
return (
<div>
<canvas ref={canvasRef} />
<div
ref={paintbrushRef}
className="paintbrush"
onMouseMove={handlePaintbrushMove}
/>
<input type="color" onChange={handleColorChange} />
</div>
);
}
In this example, the useRef hook is used to create a canvasRef and a paintbrushRef object. The ref attribute is used to assign the DOM element to the ref object, and the current property is used to access the properties of the DOM element.
The handlePaintbrushMove function uses the getBoundingClientRect method to get the position of the paintbrush element on the canvas, and the style property is used to update the top and left CSS properties. The handleColorChange function uses the value property of the input element to update the backgroundColor CSS property of the paintbrush element.
I hope this helps to clarify the concept of the useRef hook in React.
Top comments (1)
I thought this article was meant for the useReducer React hook?