By default, React will be handling all the DOM manipulation automatically, and you only need to describe what the UI should look like. But in some cases, you might need to access and manipulate the DOM manually, such as accessing the size of an element, implementing drag and drop, managing scroll positions, and so on.
Refs, short for references, are used to directly access and manipulate DOM elements or components without using the standard React state and props system.
Declaring refs
Refs are created with the useRef()
hook, which can be imported like this:
1import { useRef } from "react";
Inside your component, declare a ref like this:
1export default function App() {
2 const divRef = useRef(null);
3
4 return (. . .);
5}
useRef()
returns an object with a current
property, which is supposed to point to a DOM node. But for now, we are initializing it to be null
.
Tieing refs to DOM nodes
You can then assign a DOM node to our divRef.current
by specifying a ref
attribute.