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 :)