Check all checkboxes

We get the checkboxes from an array of results called list. We use one of the array values to set the checked states and hold it in a variable called isCheck.

All checkboxes in the list have an onChange function called selectCheckbox which sets the checkbox ID in the isCheck array when checked and removes when unchecked.

IMPORTANT: To control the selecting all checkboxes, you need to add a checked attribute onto each individual checkbox that checks if the isCheck array includes the current array value.

In the main component below we have the select all checkbox. We have an onChange function called selectAll which toggles the true/false value for isCheckAll variable. Then it sets all checkboxes or empties all checkboxes array of isCheck depending on the true/false value of isCheckAll.

import React, { lazy, useEffect, useState } from 'react';
import axios from 'axios';

const MyList = lazy(() => import('../../components/MyList/MyList'));

const YourComponent = props => {
	const [isCheckAll, setIsCheckAll] = useState(false);
	const [isCheck, setIsCheck] = useState([]);
	var [list, setList] = useState([]);
	useEffect(() => {
		getRows()
	}, []);
	function getRows() {
		let getUrl = 'https://domain.com/getrows.php';
		axios({
			method: "get",
			url: getUrl,
		}).then((response) => {
			let data = response.data;
			setList(data.listRows);
		}, (error) => {
			console.log(error)
		})
	}
	const selectAll = e => {
		setIsCheckAll(!isCheckAll);
		setIsCheck(list.map(row => row.id_pg));
		if (isCheckAll) {
		  setIsCheck([]);
		}
	};
	return (
		<>
			<input
				id="selectAllCheckbox"
				name="selectAllCheckbox"
				type="checkbox"
				value=""
				className="form-check-input"
				onChange={selectAll}
			/>
			{list.length > 0 &&
			<MyList 
				list={list} 
				isCheck={isCheck}
				setIsCheck={setIsCheck.bind(this)} 
			/>
			}
		</>
	)
}
export default YourComponent;

Next create the checkboxes list component:

import React from 'react'
import './List.css'; 

const MyList = props => {
	var list= props.list;
	const isCheck = props.isCheck;

	const selectCheckbox = e => {
		const { id, checked } = e.target;
		props.setIsCheck([...isCheck, id]);
		if (!checked) {
			props.setIsCheck(isCheck.filter(item => item !== id));
		}
	};
	console.log(isCheck);
    return ( 
		<>
		{list.map((row,i) => {
			return (
			<div key={i} className="row">
				<div className="col-1">
					<input
						id={row.id_pg}
						name="select"
						type="checkbox"
						className="form-check-input"
						onChange={selectCheckbox}
						checked={isCheck.includes(row.id_pg)}
					/>
				</div>
				<div className="col-11">
				{row.name}
				</div>
			</div>
			);
		})}
		</>
    );  
}  
export default MyList

Leave a Reply

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