0

I have rendered a list of checkboxes and i am trying to setup an onChange which tracks the selected input and turns the value to true. But i keep getting an error message and also warning with needing a unique key even though i am passing the index.

This is the CodeSandbox

Please check this complete Code:-

import React from "react";
import "./styles.css";

class App extends React.Component {
  state = {
    checkboxes: [
      { name: "Check 1", value: false },
      { name: "Check 2", value: false },
      { name: "Check 3", value: false }
    ]
  };

  checkboxStateHandler = (event, idx) => {
    const { checkbox } = this.state;
    checkbox.checkboxes[idx] = event.target.checked;
    this.setState({
      checkbox
    });
  };

  renderCheckboxes = () => {
    return this.state.checkboxes.map((cb, index) => (
      <label>
        {cb.name}
        <input
          type="checkbox"
          key={index}
          checked={cb.value}
          onChange={this.checkboxStateHandler}
        />
      </label>
    ));
  };

  render() {
    return <div>{this.renderCheckboxes()}</div>;
  }
}

export default App;

Any help will be appreciated. Thank you :)

1
  • Tried to run your code, once I've clicked the first checkbox got undefined error for checkbox. Commented Jun 18, 2020 at 1:32

2 Answers 2

2

This will work for you:

import React from "react";
import "./styles.css";

class App extends React.Component {
  state = {
    checkboxes: [
      { name: "Check 1", value: false },
      { name: "Check 2", value: false },
      { name: "Check 3", value: false }
    ]
  };

  checkboxStateHandler = (event, idx) => {
    const { checkboxes } = this.state;
    checkboxes[idx] = {
        ...checkboxes[idx],
        value: event.target.checked,
    }
    this.setState({
      checkboxes
    });
  };

  renderCheckboxes = () => {
    return this.state.checkboxes.map((cb, index) => (
      <label>
        {cb.name}
        <input
          type="checkbox"
          key={index}
          checked={cb.value}
          onChange={e => this.checkboxStateHandler(e, index)}
        />
      </label>
    ));
  };

  render() {
    return <div>{this.renderCheckboxes()}</div>;
  }
}

export default App;

You must send the event and index to the method in order to change the value, also checkboxStateHandler needs a little changes.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much!! i am still getting the key issue, maybe i'll just try passing an id.
@TreeHuggerRick, For key issue you need to make key={index} to label and not input element.. Check my below answer and sandbox..
0

There are few changes needs to be done under map method,

-> Assign key to the immediate parent under map method and in your case it is label

 <label key={index}>
    ....
 </label>

-> Then you have to modify the onChange value like,

<input
 type="checkbox"
 checked={cb.value}
 onChange={(e) => this.checkboxStateHandler(e,index)}
/>

Here the event and index needs to passed down as an arguments.

-> Then in checkboxStateHandler function get the parameters and assign the event.target.checked value to checkboxes[idx].value

  checkboxStateHandler = (event, idx) => {
    const { checkboxes } = this.state;
    checkboxes[idx].value = event.target.checked;
    this.setState({
      checkboxes
    });
  };

The above code will get rid of all warnings and errors.

Forked codesandbox here..

1 Comment

You are awesome. setting the key on label worked!! accepting this as an answer.

Your Answer

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