bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/React/React Core
React•React Core

React Forms - Radio

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind React Forms - Radio?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ { useState } from 'react';
3Order

Put the learning moves in the order that makes the concept easiest to apply.

You control radio buttons based on whether the radio button's value matches the selected value in your state.
All radio buttons in a group should share the same name attribute.
Radio buttons are typically used in groups where only one option can be selected.

Radio

Radio buttons are typically used in groups where only one option can be selected.

All radio buttons in a group should share the same name attribute.

You control radio buttons based on whether the radio button's value matches the selected value in your state.

Example

React uses the checked attribute to control the radio button:

import { useState } from 'react';
import { createRoot } from 'react-dom/client';
function MyForm() {
 const [selectedFruit, setSelectedFruit] = useState('banana');
 const handleChange = (event) => {
 setSelectedFruit(event.target.value);
 };
 const handleSubmit = (event) => {
 alert(`Your favorite fruit is: ${selectedFruit}`);
 event.preventDefault();
 };
 return ( <form onSubmit={handleSubmit}> <p>Select your favorite fruit:</p> <label> <input
 type="radio"
 name="fruit"
 value="apple"
 checked={selectedFruit === 'apple'}
 onChange={handleChange}
 /> Apple
 </label> <br /> <label> <input
 type="radio"
 name="fruit"
 value="banana"
 checked={selectedFruit === 'banana'}
 onChange={handleChange}
 /> Banana
 </label> <br /> <label> <input
 type="radio"
 name="fruit"
 value="cherry"
 checked={selectedFruit === 'cherry'}
 onChange={handleChange}
 /> Cherry
 </label> <br /> <button type="submit">Submit</button> </form> );
}
createRoot(document.getElementById('root')).render( <MyForm /> );

Previous

React Forms - Checkbox

Next

React Portals