A short React tutorial by example for beginners about using a radio button in React. First of all, a radio button is just an HTML input field with the type of radio which can be rendered in Reactâs JSX:
What may be missing is an associated label to signal the user what value is changed with this radio button:
In your browser, this radio button can already change its checked state. However, this is just the radio buttonâs internal HTML state which isnât controlled by React yet. Letâs change this by transforming this radio button from being uncontrolled to controlled :
By using Reactâs useState Hook and an event handler , we can keep track of the radio buttonâs value via Reactâs state . Next we may want to create a Radio Button component which can be used more than once throughout a React project. Therefore, we will extract it as a new function component and pass the necessary props to it:
Our Radio Button component is a reusable component now. For example, if you would give your input field some CSS style in React , every Radio Button component which is used in your React project would use the same style.
If you would want to create a radio button group now, you could just use multiple Radio Button components side by side and maybe style them with some border and some alignment, so that a user perceives them as a group of radio buttons:
If you want to enforce that only one radio button can be checked for the radio button group, you need to change it the following way:
Thatâs is it for creating a Radio Button component in React. If you are a beginner in React, I hope this tutorial helped you to understand some concepts and patterns!