So I have these sets of checkboxes for 3 different categories. 1 is "types", 1 is "Price" and the other is "Categories". they work perfectly. I have created a separate checkbox component and data is passed there without any problem.
The problem is when I click the checkbox and data is rendered but when I click the dropdown in the index page once and then press it again the data is the same as expected but the clicked style by that I mean"checked" is applied to all the checkboxes. is there any way to overcome this?
this is the separate checkbox component
import React, { useState } from "react";
interface Props {
isChecked?: boolean;
handleClick?: any;
label: string;
className?: string;
labelClassName: string;
handleChange?: any
}
const Checkbox = ({isChecked,handleClick,label,labelClassName,handleChange}: Props) => {
const [checking,setChecking]=useState(isChecked)
return (
<div>
<input
type="checkbox"
id={label}
checked={checking}
onClick={()=>{handleClick();setChecking(!checking)}}
onChange={handleChange}
className={`space-x-3 text-gray-400 bg-gray-800 border rounded border-stone-200 $`}
/>
<label className={labelClassName} htmlFor={label}>{label}</label>
</div>
);
};
export default Checkbox;
Main Index Page
// these states are for dropdown/dropup styling
const [categoryOpts, setCategoryOpts]= useState(true);
const [typeOpts, setTypeOpts]= useState(true);
const [priceOpts, setPriceOpts]= useState(true);
const [checking,setChecking]=useState(false)
const handleCheckChange=()=>{
setChecking(!checking)
}
index (){
<div>
// this is for showing/hiding price option
<div className='flex justify-between cursor-pointer' onClick={()=>setPriceOpts(!priceOpts)}>
<Text as='h5' tag='h2'>
Price
</Text>
{priceOpts?
<dropdown icon up/>
</svg> :
<dropdown icon down>
</svg>
}
</div>
// price option mapping that comes from api source.
{ priceOpts?
<div className='flex flex-col gap-2'>
{checkboxes.map(({ label, onClick, key }) =>
<div key={key}>
<Checkbox
labelClassName='text-sm text-gray-400 ml-3'
label={label}
handleClick={onClick}
isChecked={checking}
handleChange={handleCheckChange}
/>
</div>
)}
</div>: ''
}
</div>
}
<Checkbox
labelClassName="text-sm text-gray-400 ml-3"
label={label}
handleClick={onClick}
isChecked={checking} // this is the problem
handleChange={handleCheckChange}
/>;
You're setting checking prop using the same value for all your checkboxes in the main index page.
You need to have a checking parameter for each checkbox that you're rendering
{checkboxes.map(({ label, onClick, key }) right here. It should contain the state on whether the checkbox is checked or not. Like this
{checkboxes.map(({ label, onClick, key, checking })
You have to rework your checkboxes structure and checkbox even handling