Accessibility in React
In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
Prerequisites:
Familiarity with the core HTML,
CSS, and
JavaScript languages, and the terminal/command line.
Learning outcomes:
Implementing keyboard accessibility in React.
Including keyboard users
At this point, we've implemented all the features we set out to implement. Users can add a new task, check and uncheck tasks, delete tasks, or edit task names. Also, they can filter their task list by all, active, or completed tasks.
Or, at least, they can do all of these things with a mouse. Unfortunately, these features are not very accessible to keyboard-only users. Let's explore this now.
Exploring the keyboard usability problem
Start by clicking on the input at the top of our app, as if you're going to add a new task. You'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element. Press the
Tab key, and you will see the outline appear around the "Add" button beneath the input. This shows you that the browser's focus has moved.
Press
Tab a few more times, and you will see this dashed focus indicator move between each of the filter buttons. Keep going until the focus indicator is around the first "Edit" button. Press
Enter.
The
component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task.
But where did our focus indicator go?
When we switch between templates in our
component, we completely remove the elements from the old template and replace them with the elements from the new template. That means the element that we were focused on no longer exists, so there's no visual cue as to where the browser's focus is. This could confuse a wide variety of users — particularly users who rely on the keyboard, or users who use assistive technology.
To improve the experience for keyboard and assistive technology users, we should manage the browser's focus ourselves.
Aside: a note on our focus indicator
If you click the "All", "Active", or "Completed" filter buttons with your mouse, you won't see a visible focus indicator, but you will do if you move between them with the
Tab key on your keyboard. Don't worry — your code isn't broken!
Our CSS file uses the :focus-visible pseudo-class to provide custom styling for the focus indicator, and the browser uses a set of internal rules to determine when to show it to the user. Generally, the browser will show a focus indicator in response to keyboard input, and might show it in response to mouse input.
elements don't show a focus indicator in response to mouse input, while
elements do.
The behavior of
:focus-visible is more selective than the older :focus pseudo-class, with which you might be more familiar.
:focus shows a focus indicator in many more situations, and you can use it instead of or in combination with
:focus-visible if you prefer.
Focusing between templates
When a user changes the
template from viewing to editing, we should focus on the
used to rename it; when they change back from editing to viewing, we should move focus back to the "Edit" button.
Targeting our elements
Up to this point, we've been writing JSX components and letting React build the resulting DOM behind the scenes. Most of the time, we don't need to target specific elements in the DOM because we can use React's state and props to control what gets rendered. To manage focus, however, we do need to be able to target specific DOM elements.
This is where the
useRef() hook comes in.
First, change the
import statement at the top of
Todo.jsx so that it includes
useRef:
import { useRef, useState } from "react";
useRef() creates an object with a single property:
current. Refs can store any values we want them to, and we can look up those values later. We can even store references to DOM elements, which is exactly what we're going to do here.
Next, create two new constants beneath the
useState() hooks in your
Todo() function. Each should be a ref – one for the "Edit" button in the view template and one for the edit field in the editing template.
const editFieldRef = useRef(null);
const editButtonRef = useRef(null);
These refs have a default value of
null to make it clear that they'll be empty until they're attached to their DOM elements. To attach them to their elements, we'll add the special
ref attribute to each element's JSX, and set the values of those attributes to the appropriately named
ref objects.
Update the
in your editing template so that it reads like this:
Update the "Edit" button in your view template so that it reads like this:
setEditing(true)}
ref={editButtonRef}>
Edit {props.name}
Doing this will populate our
editFieldRef and
editButtonRef with references to the DOM elements they're attached to, but only after React has rendered the component. Test that out for yourself: add the following line somewhere in the body of your
Todo() function, below where
editButtonRef is initialized:
console.log(editButtonRef.current);
You'll see that the value of
editButtonRef.current is
null when the component first renders, but if you click an "Edit" button, it will log the
element to the console. This is because the ref is populated only after the component renders, and clicking the "Edit" button causes the component to re-render. Be sure to delete this log before moving on.
NOTE:
Your logs will appear 6 times because we have 3 instances of
in our app and React renders our components twice in development.
We're getting closer! To take advantage of our newly referenced elements, we need to use another React hook:
useEffect().
Implementing
useEffect()
useEffect() is so named because it runs any side-effects that we'd like to add to the render process but which can't be run inside the main function body.
useEffect() runs right after a component renders, meaning the DOM elements we referenced in the previous section will be available for us to use.
Change the import statement of
Todo.jsx again to add
useEffect:
import { useEffect, useRef, useState } from "react";
useEffect() takes a function as an argument; this function is executed after the component renders. To demonstrate this, put the following
useEffect() call just above the
return statement in the body of
Todo(), and pass a function into it that logs the words "side effect" to your console:
useEffect(() => {
console.log("side effect");
});
To illustrate the difference between the main render process and code run inside
useEffect(), add another log – put this one below the previous addition:
console.log("main render");
Now, open the app in your browser. You should see both messages in your console, with each one repeating multiple times. Note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code.
main render Todo.jsx
side effect Todo.jsx
Again, the logs are ordered this way because code inside
useEffect() runs after the component renders. This takes some getting used to, just keep it in mind as you move forward. For now, delete
console.log("main render") and we'll move on to implementing our focus management.
Focusing on our editing field
Now that we know our
useEffect() hook works, we can manage focus with it. As a reminder, we want to focus on the editing field when we switch to the editing template.
Update your existing
useEffect() hook so that it reads like this:
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
}
}, [isEditing]);
These changes make it so that, if
isEditing is true, React reads the current value of the
editFieldRef and moves browser focus to it. We also pass an array into
useEffect() as a second argument. This array is a list of values
useEffect() should depend on. With these values included,
useEffect() will only run when one of those values changes. We only want to change focus when the value of
isEditing changes.
Try it now: use the
Tab key to navigate to one of the "Edit" buttons, then press
Enter. You should see the
component switch to its editing template, and the browser focus indicator should appear around the
element!
Moving focus back to the edit button
At first glance, getting React to move focus back to our "Edit" button when the edit is saved or canceled appears deceptively easy. Surely we could add a condition to our
useEffect to focus on the edit button if
isEditing is
false? Let's try it now — update your
useEffect() call like so:
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
} else {
editButtonRef.current.focus();
}
}, [isEditing]);
This kind of works. If you use your keyboard to trigger the "Edit" button (remember:
Tab to it and press
Enter), you'll see that your focus moves between the Edit
and "Edit" button as you start and end an edit. However, you may have noticed a new problem — the "Edit" button in the final
component is focused immediately on page load before we even interact with the app!
Our
useEffect() hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that
isEditing is
false, and focuses the "Edit" button. There are three instances of
, and focus is given to the "Edit" button of the one that renders last.
We need to refactor our approach so that focus changes only when
isEditing changes from one value to another.
More robust focus management
To meet our refined criteria, we need to know not just the value of
isEditing, but also when that value has changed. To do that, we need to be able to read the previous value of the
isEditing constant. Using pseudocode, our logic should be something like this:
if (wasNotEditingBefore && isEditingNow) {
focusOnEditField();
} else if (wasEditingBefore && isNotEditingNow) {
focusOnEditButton();
}
The React team has discussed ways to get a component's previous state, and provided an example hook we can use for the job.
Enter
usePrevious()
Paste the following code near the top of
Todo.jsx, above your
Todo() function.
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
usePrevious() is a custom hook that tracks a value across renders. It:
Uses the
useRef() hook to create an empty
ref.
Returns the
ref's
current value to the component that called it.
Calls
useEffect() and updates the value stored in
ref.current after each rendering of the calling component.
The behavior of
useEffect() is key to this functionality. Because
ref.current is updated inside a
useEffect() call, it's always one step behind whatever value is in the component's main render cycle – hence the name
usePrevious().
Using
usePrevious()
Now we can define a
wasEditing constant to track the previous value of
isEditing; this is achieved by calling
usePrevious with
isEditing as an argument. Add the following inside
Todo(), below the
useRef lines:
const wasEditing = usePrevious(isEditing);
You can see how
usePrevious() behaves by adding a console log beneath this line:
console.log(wasEditing);
In this log, the
current value of
wasEditing will always be the previous value of
isEditing. Click on the "Edit" and "Cancel" button a few times to watch it change, then delete this log when you're ready to move on.
With this
wasEditing constant, we can update our
useEffect() hook to implement the pseudocode we discussed before:
useEffect(() => {
if (!wasEditing && isEditing) {
editFieldRef.current.focus();
} else if (wasEditing && !isEditing) {
editButtonRef.current.focus();
}
}, [wasEditing, isEditing]);
Note that the logic of
useEffect() now depends on
wasEditing, so we provide it in the array of dependencies.
Try using your keyboard to activate the "Edit" and "Cancel" buttons in the
component; you'll see the browser focus indicator move appropriately, without the problem we discussed at the start of this section.
Focusing when the user deletes a task
There's one last keyboard experience gap: when a user deletes a task from the list, the focus vanishes. We're going to follow a pattern similar to our previous changes: we'll make a new ref, and utilize our
usePrevious() hook, so that we can focus on the list heading whenever a user deletes a task.
Why the list heading?
Sometimes, the place we want to send our focus to is obvious: when we toggled our
templates, we had an origin point to "go back" to — the "Edit" button. In this case however, since we're completely removing elements from the DOM, we have no place to go back to. The next best thing is an intuitive location somewhere nearby. The list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left.
Creating our ref
Import the
useRef() and
useEffect() hooks into
App.jsx — you'll need them both below:
import { useState, useRef, useEffect } from "react";
Next, declare a new ref inside the
App() function, just above the
return statement:
const listHeadingRef = useRef(null);
Prepare the heading
Heading elements like our