mercredi 12 septembre 2018

Uncheck checkbox on check of another checkbox in React

I am working on a react component and I have 3 checkboxes. My requirement is that when 3rd checkbox is checked, any of the first 2 checkboxes that was checked previously should become unchecked and disabled. And when 3rd checkbox is unchecked, any checkbox that was checked previously, should get checked again.

First two checkboxes are dynamically populated from an array like this :

{credits.map((section, i) => (
          <p key={i}>
            <input
              disabled={this.state.checkedChkBox === "noneApply"}
              id={`amtChk${i + 1}`}
              type="checkbox"
              name="amountCheck"
              value={`${section.amount} - ${section.date}`}
            />
            <label htmlFor={`amtChk${i + 1}`} id={`amtLbl${i + 1}`}>
              {section.amount}
            </label>
          </p>
        ))}

3rd checkbox looks like this

<input onChange={evt => this.noneApplyChk(evt)} id="noneApply" type="checkbox" name="noneApplyCheck" value="noneApply" />
        <label htmlFor="noneApply" id="noneApplyLbl">
          None apply
        </label>

In my constructor, I have defined a state to handle disabling of first 2 checkboxes.

constructor(props) {
super(props);
this.state = { checkedChkBox: "" };

}

This is how my noneApplyChk function looks like

noneApplyChk(evt) {
if (this.state.checkedChkBox === "noneApply") {
  this.setState({ checkedChkBox: "" });
} else {
  this.setState({ checkedChkBox: evt.target.id });
}

}

It does the disabling/enabling of first 2 checkboxes well, but I am still not able to find a way to check/uncheck first 2 checkboxes on uncheck/check of the 3rd checkbox. I also tried checked={this.state.checkedChkBox !== "noneApply" || this.state.checkedChkBox !== ""} on the first 2 checkboxes along with onChange event. That didn't help either.

Please let me know if anyone has any ideas.

PS: I want to do it the react way and not the jquery way.




Aucun commentaire:

Enregistrer un commentaire