Categories
JavaScript React

Set the Default Checked Value of a React Radio Button

Spread the love

To create a radio button group with React and set the default checked value of it, we have to set the value to the state that we want.

Then we’ve to set the checked prop to be the expression to compare the value of the radio button with the currently selected value.

This way, React will check the right one.

We also need an onChange handler to update the state to the right value.

To do all that, we write:

import React, { useState } from "react";

const fruits = ["orange", "apple", "grape"];

export default function App() {
  const [fruit, setFruit] = useState("apple");
  return (
    <div className="App">
      {fruits.map(f => (
        <>
          <input
            type="radio"
            name="fruit"
            value={f}
            checked={fruit === f}
            onChange={e => setFruit(e.currentTarget.value)}
          />{" "}
          {f}
        </>
      ))}
      <p>{fruit}</p>
    </div>
  );
}

We have the fruits array, which we use to map the values to radio buttons.

Radio buttons are input elements with type 'radio'.

The name attribute also have to be set to the same name so that we know that they’re in the same group.

The value attribute is set to the fruit state, so that we can update the checked value by comparison fruit with the value of the value attribute of the radio button.

We have:

onChange={e => setFruit(e.currentTarget.value)}

which gets the e.currentTarget.value property, which has the currently checked radio buttons’ value and set it as the value of the fruit state.

This will update the radio button when we click on it.

Then we display the value of the radio button that’s checked below so that we can see what we actually selected.

To set the default value, we just set the initial value of the fruit state since we used that as the value of the value prop.

The button that’s clicked should have the same value that’s displayed.

To set the default value of a React radio button element, we just have to set the value prop to the state value that we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “Set the Default Checked Value of a React Radio Button”

Leave a Reply

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