This comprehensive tutorial will teach you how to create dynamic multiple checkboxes using functional components and React hooks in a React TypeScript application.
We are going to show you how to build a dynamic checkboxes list where checkboxes are being created by retrieving the data from the server with the help of Fetch API.
To work with multiple checkboxes in React functional component, we need to manage the component state. We will handle the checkboxes state using useEffect and useState hooks.
To update the checkboxes state, we will take the help of the onChange event handler. This will help us delete or remove the checkboxes from the dynamic checkbox list in React.
React TypeScript Dynamic Checkbox List Example
- Step 1: Download React Project
- Step 2: Make Component File
- Step 3: Install Bootstrap Library
- Step 4: Handle Multiple Checkbox Values in React
- Step 5: Register Dynamic Checkbox Component
- Step 6: Start React Server
Download React Project
Open the terminal; on the console screen, type the command, then run the command to install a new React TypeScript application.
npx create-react-app react_ts_demo --template typescript
Get into the application folder.
cd react_ts_demo
Make Component File
In this step, get inside the src directory of your React TypeScript app.
Here you have to create the components folder, create the MultiCheckbox.tsx file, then add code to create a functional component.
import React from 'react'
function MultiCheckbox() {
return (
<div>
</div>
)
}
export default MultiCheckbox
Install Bootstrap Library
Bootstrap is ideally used for styling the UI layout; therefore, we are going to install bootstrap in React.
npm install bootstrap
Open the App.js file, then import the bootstrap CSS path as given below.
import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import MultiCheckbox from "./components/MultiCheckbox";
function App() {
return (
<div className="container mt-5">
</div>
);
}
export default App;
Handle Multiple Checkbox Values in React
In this step, we have to get into the components/MultiCheckbox.tsx file, then add all the suggested code into the file.
import React, { useState, useEffect } from "react";
const Endpoint = "https://jsonplaceholder.typicode.com/users";
interface User {
id: any;
name: string;
}
const MultiCheckbox = () => {
const [cdData, setCbData] = useState<Array<User>>([]);
const [userId, setUserId] = useState<Array<any>>([]);
useEffect(() => {
const getUsers = async (url: string) => {
try {
const res = await fetch(url);
const data = await res.json();
setCbData(data);
} catch (error) {
console.log(error);
}
};
getUsers(Endpoint);
}, []);
const selectUser = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedId = parseInt(event.target.value);
if (userId.includes(selectedId)) {
const newIds = userId.filter((id) => id !== selectedId);
setUserId(newIds);
} else {
const newIds = [...userId];
newIds.push(selectedId);
setUserId(newIds);
}
};
const deleteCb = () => {
const remainingcdData: User[] = cdData.filter(
(user: any) => !userId.includes(user.id)
);
setCbData(remainingcdData);
};
return (
<div style={styles.container}>
{cdData.length === 0 && <h4>Loading...</h4>}
{cdData.length > 0 &&
cdData.map((user: any) => (
<div style={styles.userWrapper} key={user.id}>
<span style={styles.id}>{user.id}</span>
<span style={styles.name}>{user.name}</span>
<span>
<input
type="checkbox"
value={user.id}
onChange={selectUser}
checked={userId.includes(user.id) ? true : false}
/>
</span>
</div>
))}
<button style={styles.btn} onClick={deleteCb}>
Delete User
</button>
</div>
);
};
const styles: { [key: string]: React.CSSProperties } = {
userWrapper: {
width: "100%",
display: "flex",
justifyContent: "space-between",
margin: "8px 0",
padding: "12px 20px",
backgroundColor: "#efefef",
},
id: {
width: "10%",
},
name: {
width: "70%",
},
btn: {
marginTop: 25,
color: "#ffffff",
border: "none",
width: "100%",
cursor: "pointer",
padding: "16px 32px",
backgroundColor: "blue",
},
};
export default MultiCheckbox;
Register Multi Checkbox Component
Head over to App.js file, the global component of the React. In this file, you have to import the MultiCheckbox component in React global component.
import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import MultiCheckbox from "./components/MultiCheckbox";
function App() {
return (
<div className="container mt-5">
<h2>React TypeScript Multiple Dynamic Checkbox Example</h2>
<MultiCheckbox />
</div>
);
}
export default App;
Start React Server
Move on to the terminal, then execute the following command to start the React server.
npm start
You may use the following URL to view the app.
http://localhost:3000
Conclusion
In this React checkboxes example tutorial, we learned how to create a dynamic checkbox list component that makes a list of checkboxes. Not only but also how to set the onChange event handler to manage the checkboxes in React.