Reputation: 3507
I have this checkbox component!
const CheckBox = props =>{
var [show,setshow] = useState(false);
const option = props.name.replace(/\s/g, '');
return(
<div className="filter-option" onClick={e=>setshow(!show)} data={option}>
<div className={show?"check-bock checked":"check-bock"} >
<i className="fa fa-check"></i>
</div>
<label className="font-20">{props.name}</label>
</div>
)
}
The checked class will show checkmark, but if i want to render multiple checkboxes the problem is all checkboxes are checked at once!
I want only one checked and others unchecked!
Upvotes: 0
Views: 642
Reputation: 281854
The solution is to keep in state which checkbox is checked and store this state in parent from where all checkboxes are rendered
const CheckBox = props =>{
const option = props.name.replace(/\s/g, '');
return(
<div className="filter-option" onClick={e=>props.setshow(prev => props.name == prev? '': props.name)} data={option}>
<div className={props.show?"check-bock checked":"check-bock"} >
<i className="fa fa-check"></i>
</div>
<label className="font-20">{props.name}</label>
</div>
)
}
const Parent = () => {
var [show,setshow] = useState('');
return (
<>
<Checkbox name="first" show={"first" === show} setShow={setShow}/>
<Checkbox name="second" show={"second" === show} setShow={setShow}/>
</>
)
}
Upvotes: 1