1

I render some checkbox via json data with map:

Data.FacData.map((v, i) => (
  <div key={i} className="CheckBox">
    <input
      type="checkbox"
      name="Facilities"
      value={v.id}
      onChange={this.getFacilities}
      id={"Facilities-"+v.id}
      />
    <label htmlFor={"Facilities-" + v.id}>{v.name}</label>
  </div>
))

JSFiddle

It work fine and you can select any chekcbox and get it as array on console log (I handle and save it to database somehow) , but now I want to get what user selected before, from database (api), I got this data (object)

facilities: "1,3"

This mean user select checkbox 1 and 3, I want to make checkbox checked, what I tried is use defaultChecked property, but it select all checkbox not only 1,3, any solution?

JSFiddle

1

1 Answer 1

2

update your code like this or refer https://jsfiddle.net/L7y2m8zr/17/ you need to convert the value string to array using split

componentDidMount() {
  /*get data from api*/
  const data = "1,3"
  const newValues = data.split(",").map(n => parseInt(n))
  this.setState({
    facilitiesValue: newValues
  });
}

also you can set the defaultChecked or checked value based on whether the array includes the given id, instead of just passing the array or string( since this is code and not magic :) )

return (
    <div>
    {
        Data.FacData.map((v, i) => (
        <div key={i} className="CheckBox">
             <input
             type="checkbox"
             name="Facilities"
             value={v.id}
             onChange={this.getFacilities}
             id={"Facilities-"+v.id}
             checked = {this.state.facilitiesValue.includes(parseInt(v.id))} 
            />
             <label htmlFor={"Facilities-" + v.id}>{v.name}</label>
        </div>
        ))
     }
    </div>
)

also update the onchange handler, to update the state

getFacilities = (e) => {
  const checked = this.state.facilitiesValue;
  let index;

  if (e.target.checked) {
    checked.push(parseInt(e.target.value))
  } else {
    index = checked.indexOf(parseInt(e.target.value))
    checked.splice(index, 1)
  }
  console.log(checked)
  this.setState({
    facilitiesValue: [...checked]
  })
};
Sign up to request clarification or add additional context in comments.

2 Comments

Only issue is not able to checked/unchecked any checkbox
Thanks for your great answer, and your help

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.