In this article, we will learn how to retrieve values from multiple checkboxes in React.
Checkboxes can be seen when one wants to select some options according to their choices. As you browse YouTube, you may have come across a survey that consists of a question and several boxes from which you can select one or more options based on your preferences and experience. These boxes are called checkboxes.
There may be a need to create forms containing these checkboxes in certain applications. We need to get hold of this data to do something with it. For instance, if you go to any Pizza application and there are several options to select the toppings, you will be charged for the toppings that you choose. It is necessary to fetch the values you selected so that the pizza of your choice can be delivered and you are billed accordingly.
Let’s see how to determine the checked values using the following example.
Approach: We will create a simple form that asks the user to select the programming languages they are familiar with. We will display the selected values in a textbox in this example.
- Create a react app.
- Make a form with checkboxes.
- Check multiple boxes.
- Display the checked values in the textbox.
Start by following the steps below:
Step 1: Make a project directory, head over to the terminal, and create a react app named ” form-check” using the following command:
npx create-react-app form-check
After the form-check app is created , switch to the new folder form-check by typing the command below:
cd form-check
Step 2: Modify Your project structure. The Directory structure currently looks like this:
We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:
Step 3: Add code in your index.html file.
Include the following code in your index.html file, located in the public folder of your project directory. We will use bootstrap to build our form component. Import the bootstrap CDN into your index.html as follows:
Links: Put the following code at the end of the body.
<script src=”https://code.jquery.com/jquery-3.2.1.slim.min.js”
integrity=sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN”
crossorigin=”anonymous”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js”
integrity=”sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q”
crossorigin=”anonymous”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js”
integrity=”sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl”
crossorigin=”anonymous”></script>
Links: Put the following code at the end of the head:
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css”
integrity=”sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm”crossorigin=”anonymous”>
This is how your index.html should look:
index.html
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "utf-8" /> < meta name = "viewport" content = "width=device-width, initial-scale=1" /> < meta name = "theme-color" content = "#000000" /> < meta name = "description" content = "Web site created using create-react-app" /> < link rel = "stylesheet" href = integrity = "sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin = "anonymous" > < title >React App</ title > </ head > < body > < div id = "root" ></ div > < script src = integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous" > </ script > < script src = integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous" > </ script > < script src = integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin = "anonymous" > </ script > </ body > </ html > |
Step 4: Making the form component in App.js file.
We will create a form component in the App.js file. Users can select several programming languages from the form based on their preferences. As we’ll be modifying the behavior of our component dynamically based on whether the user checks or unchecks the box, we’ll need to store this value in the app and update the same. Therefore, we will use the useState hooks to manage our app’s state and track its changes. We will import the useState hook from react as follows:
import React, { useState } from "react";
Then we will call the useState() function. The initial state is passed to the useState() Hook. It returns the current state and a function to update it. We will declare a state variable called userinfo, and set it to an object of empty arrays languages and response. The language array preserves the checked value, and the response array uses the same checked values to display in the textbox. We can call setUserInfo to update our current state. This will be expressed as:
const [userinfo, setUserInfo] = useState({ languages:[], response:[] });
All input tags for the checkbox will have the same name attribute, i.e. languages. We will assign the actual language names to the Value attribute, add an event handler onChange, and define a function handleChange to handle this event. In this function, we will pass an event object that consists of some properties which describe the event. e.target returns the element that triggered the event. e.target.value returns the value of the checked box, whereas e.target.checked determines whether the box is checked and returns a boolean value. We will destructure value , checked from e.target as:
const {value ,checked } = e.target;
Destructuring enables you to unpack values from an object or array. This is the same as writing e.target.value and e.target.checked. Then we will take the languages array from userinfo.
There will be two cases:
- User checks the box: If the box is checked, i.e. e.target.checked returns true, then we will update the state and pass the value of the checked box in the language and response array. With more than one language or option available, we must update the array with the new selected option, preserving the previous selected value. Therefore, we will use the Spread operator, which is represented by an array preceded by three dots. This merges the previous array into the current array. The language array will retain multiple values in this way. The response array will contain the same values as that of the language array.
- User unchecks the box: We need to remove the value from the array when the user unchecks the box. This can be accomplished using the filter function. The filter function loops through the array and includes or excludes elements based on the condition we provide. So we will pass a function with an event parameter. Now, if the checked event returns false then the value for that event is removed.
To display the checked values we have created a textarea element that takes the values from the response array. The response array stores the checked values the same as that of the language array. As the user checks the box, this textarea value gets updated with that checkbox value and is displayed in the textarea.
Write the following code in your App.js file to achieve this functionality.
App.js
import React, { useState } from "react" ; import "./App.css" ; function App() { const [userinfo, setUserInfo] = useState({ languages: [], response: [], }); const handleChange = (e) => { // Destructuring const { value, checked } = e.target; const { languages } = userinfo; console.log(`${value} is ${checked}`); // Case 1 : The user checks the box if (checked) { setUserInfo({ languages: [...languages, value], response: [...languages, value], }); } // Case 2 : The user unchecks the box else { setUserInfo({ languages: languages.filter((e) => e !== value), response: languages.filter((e) => e !== value), }); } }; return ( <> <div className= "container-fluid top " > <div className= "container mt-5 pb-5 pt-5" > <h3 className= "form-head-contact-h3 " > Your programming expertise lies in what languages?{ " " } </h3> <form> <div className= "row" > <div className= "col-md-6" > <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "Javascript" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > Javascript </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "Python" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > Python </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "Java" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > Java </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "PHP" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > PHP </label> </div> </div> <div className= "col-md-6" > <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "C#" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > C # </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "C++" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > C++ </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "C" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > C </label> </div> <div className= "form-check m-3" > <input className= "form-check-input" type= "checkbox" name= "languages" value= "Typescript" id= "flexCheckDefault" onChange={handleChange} /> <label className= "form-check-label" htmlFor= "flexCheckDefault" > Typescript </label> </div> </div> </div> <div className= "form-floating mt-3 mb-3 text-center" > <label htmlFor= "exampleFormControlTextarea1" > You're proficient in the following languages :{ " " } </label> <textarea className= "form-control text" name= "response" value={userinfo.response} placeholder= "The checkbox values will be displayed here " id= "floatingTextarea2" style={{ height: "150px" }} onChange={handleChange} ></textarea> </div> </form> </div> </div> </> ); } export default App; |
Step 5: Now, let’s style our components. Write the following code in the App.css file.
App.css
.text { width : 50% ; margin : auto ; } . top { /* margin: auto; */ margin-top : 4% ; width : 50% ; border : 2px ridge black ; background-color : #f1f1f1 ; } h 3 { text-align : center ; } .row { padding-left : 20% ; } |
Step 6: Your index.js file should look like this. The index.js file serves as the main entry point, and inside it the App.js file is rendered at the root ID of the DOM.
App.js
import React from "react" ; import ReactDOM from "react-dom" ; import App from "./App" ; ReactDOM.render(<App />, document.getElementById( "root" )); |
Step to run the application: Run our application by using the following command:
npm start
Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser.
When a box is checked, its value is displayed in the textbox at the bottom, and when the box is unchecked, its value is removed.