Creating a Radio Button Component in React
Radio buttons can be tricky, this aims to demystify them
Introduction
Styling and working with radio buttons have always been tricky business. To custom style a boring default HTML radio button, you must put in a lot of CSS and have pretty advanced CSS knowledge as well. Manipulating CSS pseudo-selectors (::before/::after) and whatnot.
To add to that, using radio buttons in React can be even more tricky. Handling change, tracking which value is selected, having the radio button checked is not so obvious in React. We’ll create our custom RadioButton component in React, in which I’ll try to clarify all aspects of a radio button.
Setup
We’ll use create-react-app to set up a blank React project. Note: this tutorial assumes you have created React projects with create-react-app before and have NodeJS and npm installed. Also, install create-react-app using npm if you haven’t already. Run the following command in your terminal
create-react-app radio_button_tut
That’ll create a folder called radio_button_tut and will initialize a new React app within with boilerplate code. Some of which we’ll remove. We’ll also install node-sass as we’ll be using SASS in our project. SASS can be used in React apps out of the box now without any additional setups or having to eject from create-react-app. Run the following command
npm install — save node-sass
After this is done, open the project folder with your favorite code editor. Let’s start by removing the boilerplates created by create-react-app. Rename the App.css and index.css files to App.scss and index.scss. Nothing really changes here other than the extension to represent a SASS file. Remove everything inside App.scss and replace it with below codes
It’s just some basic CSS resets and font setup. We also reset the pseudo-selectors, ::before and ::after otherwise the radio button styles will not take effect properly. Especially with centering the radio button selection circle. Try removing that code after we have created the CSS for the radio button.
Now, let’s create a new component inside the src folder. Create a folder named RadioButton. Inside create two more files, RadioButton.js and RadioButton.scss. Open the .scss file and copy-paste the below code.
Now, I didn’t write all these fancy CSS. I borrowed it from Hannes Kamecke on CodePen. The link to his pen => https://codepen.io/hansmaad/pen/zBdzxp
The CSS can seem complicated if your CSS game is not that strong. It uses some cool CSS features like KeyFrames for animations. The KeyFrame is used for the ripple effect on selecting the radio button. The ::before and, ::after are used in styling the radio button circle.
Open the RadioButton.js file now and paste in the following code
It’s a simple functional React component. The JSX structure is very simple, a div is wrapping the radio input element and the label element. We pass 5 props to this component. The label, value, id, isSelected and, the changed props.
The changed props is a function. This function will fire every time the radio button is changed. In vanilla JS this would be the callback function we pass to the addEventListener. The event we’re listening for here is the onChange. You can see we’re assigning the props.changed to onChange event.
The value props is self-explanatory, it’s setting the value of the input element. This value is required to evaluate what is selected and what action should we take based on this selection. It’s even passed to databases on occasions when it’s necessary to save the value.
The label props is just the label text. This makes the component reusable across our application. As we’re not hardcoding anything.
isSelected is a boolean value. It controls which radio button should be selected. We dynamically evaluate this where we use the RadioButton component, based on the value of the radio input.
The id part is interesting. Without it, the setup here will not work. The id is mainly used by the label element. It needs to know for which input is this label for. If we don’t use this, no matter how hard you press the radio button, it’ll not be selected, meaning the event associated with it, onChange will never fire. Notice the htmlFor attribute. This attribute is named just for in plain HTML. But, as for is a keyword in JS, we can’t use that. React replaces that with htmlFor. During the build, it changes it to plain for. We set the id of the input field and tell the label about it with htmlFor. If the radio buttons are generated with for loops, the id can be the index of the loop.
That’s it for the RadioButton component. Let’s use it now. Dump the code below in App.js
Ignore the inline styles here. They’re just for presentational purposes. One sets the margin and the other makes the radio buttons in a line (row) using FlexBox instead of columns.
The App component is a class component. So we can use states here and define event listeners that will be passed as props. The state is simple. It has a single property, paymentMethod. This is the value of the selected radio button. Initially, it’ll be COD as in cash on delivery. The setup here is of a fictional eCommerce website. Whereat checkout you'll be presented with payment options using radio buttons. Why radio buttons? Because you can select only one option as the payment method. You can either choose cash on delivery or QuickPay another fictional payment method. If you select QuickPay option, an input field will appear where you can enter the transaction id. When the other option is selected, the input will dissapear. We do this inside the render method in this line
const quickpay = this.state.paymentMethod === “QuickPay” ? <input type=”text” placeholder=”Enter transaction id”> : null;
It checks the state, if the value is QuickPay meaning that option is selected, the variable will hold the input element or else null. This ensures we only see this when the appropriate option is selected.
We create 2 RadioButton components here and pass in the appropriate props. Notice the isSelected props. The value here evaluates to a boolean based on the value the state holds.
We pass down a changed props which is a function. This is the event listener. We create the radioChangeHandler method which is fired each time the radio button is switched. It sets the state to the value of the radio button using event.target.value. The event passed to this function is normal JavaScript. Nothing React specific. This is passed to all event listeners once they are fired, it contains information related to that event. When the state changes we see the effect it takes in our UI.
So that’s it! Hope it helped.