1

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?

1 Answer 1

2

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>
)}
Sign up to request clarification or add additional context in comments.

2 Comments

did you have id defined in BrandList?
I am getting this error. TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.