Let’s Make a React Radio That Will Pass A11Y — Part 2
Build a radio group using React, styled-components, and Framer Motion
In Part 1, we looked at the accessibility rules for this component, coded the base structure, and handled some basic logic. In Part 2, we’ll handle the selected state, clicks, and keypresses. You can find part 3 here.
Before we continue, let’s take a quick look at where we left off in Part 1:
We can easily find out if an option is selected by looking at the
aria-checked property of the
Knowing this we can write some styles:
And we can test by setting the
aria-checked property to
Our component should look like this:
Now that we know that our styling works, we can properly set the logic for the
aria-checked property. It should be true only if the current option’s
id is the same as
6. Handle onClick Event
This part is pretty straightforward. We have to create a function that sets the
selectedId to the clicked option.
7. Handle Keypress Events
Looking at the keyboard support table from W3, we can see that for these components we have to support:
- Tab for focusing on the selected option;
- Up and Left Arrows for the previous option;
- Down and Right arrows for the next option;
- Spacebar for selecting an option.
Tab is the easiest one. We don’t have to do anything more, because we’re using the
aria-activedescendant property. So essentially every time the browser focus passes through our component, it’ll target the
Container component and that will read the active descendant element id.
In order to handle our arrow and spacebar presses, we have to first check which keycode corresponds to which key. We can do that using this site. After that, we can define an object containing our keycodes.
Next let’s associate a
onKeyDown event on our
And code the function:
Stay tuned for Part 3 where we will handle animations and make the component controlled and uncontrolled.
If I missed something, please let me know. I will do my best to keep the piece updated.