How to validate a radio button in React

You may need to validate a radio button when you are creating a form in React. Just as we have created a common component for the select field and input field in the previous article, here we will create a component for the radio button in React.

Demo Application

Output - How to validate a radio button in React - Clue Mediator
Output – How to validate a radio button in React – Clue Mediator

Steps to validate a radio button in React

  1. Create a common component
  2. Create a form using the Radio component
  3. Output

1. Create a common component

Let’s create a reusable radio component using Bootstrap where we will pass all required fields.

Same as the Input component and Select component, we have to go through a few more props to handle the validation such as isReq, errorMsg, onValidateFunc.

Radio.js

2. Create a form using the Radio component

Now it’s time to use the Radio component in the main component for gender and status selection. In the first place, we have to define two different state variables called form and error.

Let’s define the object for each property in an error state. The error object contains the following attributes.

  • isReq – For require validation
  • errorMsg – To render the error message on the screen
  • onValidateFunc – Function to handle the validation

Use the following HTML to render the form in React component.

Let’s merge all code together and see how it looks.

App.js

3. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *