Project 61 of 100 - React useRef Hook
James Hubert
Posted on April 26, 2021
Github link to project: Link
Deployed app: Link
This is my first post in over a month but an important first step to getting back into the swing of things. For the last month I've been busy on a project for work that kept me working around the clock for some weeks. I've also been visiting family for the first time since the Coronavirus pandemic began almost a year and a half ago so I used the time to hang with them.
Is it still #100days100projects if you take a break? My mind says no... but my heart is telling me yes. Ultimately, the break served me well because I spent a ton of time writing vanilla Javascript and CSS which is really helpful for React programming.
Anyway, here was the project: For today I completed phase 1 of Bob Ziroll's React typing game for the Scrimba advanced React course. This segment focuses on React hooks, and this project incorporated useState, useContext, and useRef.
All about ref
useRef
is a pre-built React hook that comes with the React library. Its purpose is to allow you to hook into a JSX element and manipulate it from elsewhere in your React application.
According to www.reactjs.org:
useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
What it essentially does is let you select a DOM element and make changes to it via Javascript like an html element. The benefit of using it over plain Javascript is that it is confined to the current React component. Chen-Tai's answer on StackOverflow summed it up pretty well for me:
The benefit is using ref has good reusability and scope. Because ref only stay in this component, when you manipulate this ref, it won't interfere other component... If you use id, it has duplicate problem.
Using ref
My application had a specific issue that when the user pressed the start button of the typing game there was no indication of where the user should begin typing, so I wanted to put the focus on the textarea.
That meant I needed a reference to the textarea DOM element so that I could use the native Javascript focus() method on it. To create a reference to the DOM element using ref
we must first import it from React. At this point my import statement looked like this:
import React, {useState,useEffect,useRef} from 'react'
Like other React hooks, to begin using the useRef hook we must first instantiate it in the component. This means, commonly, setting it equal to null
because assignment happens on the component itself with the ref
keyword. It is then stored in a variable for use later.
const textareaRef = useRef(null);
All React JSX elements will now have a ref
property available to them, so to create a reference to the textarea simply add ref
to the JSX element's properties and for the value use the variable you created when you instantiated the useRef reference. Mine looked like this:
<textarea
disabled={!isPlaying}
onChange={handleTyping}
value={text}
ref={textareaRef}
placeholder={"Press the Start button to begin the game."}
/>
As you can see, the ref property on the element is being assigned to the variable we created above at the component level.
.current
One of the main ways this differed in usage from just grabbing a DOM element by its ID was the .current property available on the reference variable. We need to use .current
because this is literally where the reference is stored. Otherwise, it's just a variable.
So to access the reference and manipulate any properties on it dynamically, when I start the game I also use the focus
method:
const startGame = () => {
...
textareaRef.current.focus()
}
So this is one way to reference a DOM node and make changes to it from elsewhere in the component- the React way!
I was happy to finally get around to ref
because it's definitely one of the top 3 or so native React Hooks.
As always, if you like content like this don't forget to add me on the Twitters. Seriously- I haven't gained a single follower since I stopped posting. I've missed you all! :)
Posted on April 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.