Reputation: 2339
I am trying to add checkboxes in my web application. Checkboxes are showing on the webpage. I want to save checkbox checked values in local storage, So I can keep checkboxes checked on page refresh. How can I do this?
{
Object.keys(catagory_products).map((item, index) => {
if (item == 'brandlist') {
return catagory_products.brandlist.map((BrandList, index) =>
// console.log(BrandList)
(
<div className="custom-control custom-checkbox ml-2">
<input
type="checkbox"
className="custom-control-input checksave"
id={`${BrandList}`}
name="brand[]"
value={`${BrandList}`}
onChange={this.toggleCheckboxChange}
autoComplete="off"
/>
<label
className="custom-control-label brandname"
htmlFor={`${BrandList}`}
>
{BrandList}
I </label>
</div>
),
);
}
});
}
Please help me how can I do this?
Upvotes: 1
Views: 3488
Reputation: 3934
Please find the following code:
componentDidMount() {
const items = {...localStorage};
this.setState({
items,
})
}
toggleCheckboxChange = (e) => {
e.preventDefault()
if (e.target.type === 'checkbox') {
localStorage.setItem({ [e.target.id]: e.target.checked })
}
}
render() {
return(
<div>
{
Object.keys(catagory_products).map((item, index) => {
if (item === 'brandlist') {
return catagory_products.brandlist.map((BrandList, index) =>
// console.log(BrandList)
(
<div className="custom-control custom-checkbox ml-2">
<input
type="checkbox"
className="custom-control-input checksave"
id={BrandList.id}
name="brand[]"
value={!!this.state[BrandList.id]}
onChange={this.toggleCheckboxChange}
autoComplete="off"
/>
<label
className="custom-control-label brandname"
htmlFor={BrandList}
>
{BrandList}
I </label>
</div>
),
);
}
});
}
</div>
)}
Upvotes: 2