What is a ref? How do you use it?
A ref is a reference to a DOM element in React.
Refs are created with the help of the useRef
hook and can be immediately placed in a variable.
This variable is then passed to a given React element (not a component) to get a reference to the underlying DOM element (that is, div, span, and so on).
The element itself and its properties are now available on the .current property of the ref.
import { useRef } from 'react'
function MyComponent() {
const ref = useRef();
useEffect(() => {
console.log(ref.current) // reference to div element
}, [])
return <div ref={ref} />
conole.log(ref.current) // reference to
}
Refs are often referred to as an "escape hatch" to be able to work with a DOM element directly. They allow us to do certain operations that can't be done through React otherwise, such as clearing or focusing an input.