0
0
Reactframework~30 mins

Handling checkboxes and radio buttons in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling checkboxes and radio buttons
📖 Scenario: You are building a simple survey form in React. The form asks users to select their favorite fruits using checkboxes and choose their preferred contact method using radio buttons.
🎯 Goal: Create a React functional component that manages the state of multiple checkboxes and a group of radio buttons. The component should update the state correctly when users select or deselect checkboxes and when they choose a radio button.
📋 What You'll Learn
Use React functional components with hooks
Manage checkbox states as an object with fruit names as keys and boolean values
Manage radio button state as a single string value
Update state correctly on user interaction
Render checkboxes and radio buttons with labels
💡 Why This Matters
🌍 Real World
Forms with checkboxes and radio buttons are common in surveys, settings pages, and user preferences in web apps.
💼 Career
Understanding how to handle multiple inputs and manage their state is essential for frontend developers working with React or similar frameworks.
Progress0 / 4 steps
1
Set up initial state for checkboxes
Create a React functional component called SurveyForm. Inside it, create a state variable called fruits using useState. Initialize fruits as an object with keys apple, banana, and orange, all set to false.
React
Need a hint?

Use useState to create fruits as an object with keys for each fruit set to false.

2
Add state for radio buttons
Inside the SurveyForm component, add a new state variable called contactMethod using useState. Initialize it with an empty string ''.
React
Need a hint?

Use useState to create contactMethod with initial value ''.

3
Handle checkbox changes
Add a function called handleFruitChange inside SurveyForm. It should take an event parameter and update the fruits state by toggling the boolean value for the fruit matching event.target.name. Use the setFruits function and spread the previous state.
React
Need a hint?

Use event destructuring to get name and checked. Update fruits state by copying previous state and changing the key matching name.

4
Render inputs and handle radio changes
Inside the SurveyForm component, return JSX that renders three checkboxes for apple, banana, and orange. Each checkbox should have name, checked bound to fruits[name], and onChange set to handleFruitChange. Also render two radio buttons for contact methods email and phone. Each radio should have name="contactMethod", value set to the method, checked bound to contactMethod === value, and onChange that updates contactMethod state using setContactMethod. Wrap inputs with labels for accessibility.
React
Need a hint?

Use label tags wrapping input elements. Bind checked and onChange properly for both checkboxes and radio buttons.