When building a React app, there are going to be times where you'll want to reference a particular part of the DOM for one reason or another. If you've written Javascript code before, you're likely very familiar with how you would go about doing this, however In React you'll have to change your ways a bit β luckily it is pretty painless β in comes the useRef hook.
How It Works
The useRef hook simply returns an object with a ".current" property which will be the DOM element or value that you plan to use at some point or another within your component. Note: useRef will not cause any re-renders, it is simply an object that holds the DOM or value you've assigned to it.
How To Use It
- Import useRef from React
- Create a variable and set the value to useRef()
- Place a ref attribute on an element (there are other ways to use this hook, but I'm simply covering the most common / simplest use case), with the value set to the variable created above
- Access the DOM element with 'variableName.current'
Example:
// 1. Importing useRef from React
import React, {useRef} from 'react';
import './App.css';
function App() {
// 2. Creating firstParagraph and secondParagraph and setting their values to useRef()
let firstParagraph = useRef()
let secondParagraph = useRef()
// 3. Placing a ref attribute "ref={}" on both paragraph tags, with the appropriate
// variable as the attribute value
return (
<div className="App">
<p ref={firstParagraph} >First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph First Paragraph </p>
<button onClick={() => firstParagraph.current.innerText = "Hi"}>Change First Paragraph Text</button>
<p ref={secondParagraph} >Second Paragraph Second Paragraph Second Paragraph Second Paragraph Second Paragraph Second Paragraph Second Paragraph Second Paragraph </p>
<button onClick={() => secondParagraph.current.style.backgroundColor = "lime"}>Change Second Paragraph Background Color</button>
</div>
);
}
// 4. Notice that within our onClick event we reference the appropriate ref
// (which is holding our DOM element) via variableName.current
// we then manipulate the DOM element just as we normally would in Vanilla JS.
export default App;
Try It Yourself
It is always easier to see this type of functionality by trying it yourself Head over to the replit, fork the repo, and experiment! Create a new ref, a new paragraph (or whatever you want), and try to connect the dots by doing something similar to whatever you end up adding to the page.
As always, refer to the docs for more clarity / a deeper dive:
Feel free to reach out on any of my socials for questions, feedback, or just to connect / say hello π.
Top comments (1)
Again, excellent short reference on refs :)