I am fetching items from an api and then displaying them to user with checkboxes. When user clicks on an item the item's value should be added to user's items array. Also by unchecking it, it should be removed from the array...
I know the logic behind checkboxes and state and arrays, however I simply cannot understand what is going wrong here in my code. My code indeed adds items to user's array but when I try to uncheck the item all of the items except the clicked item are removed...
class StepThree extends Component {
constructor(props) {
super(props);
this.state = {
selectedItems: []
};
};
handleCheckbox = e => {
let { selectedItems } = this.state;
const item = e.target.name;
if (selectedItems.includes(item)) {
const index = selectedItems.indexOf(item);
this.setState({ selectedItems: selectedItems.splice(index, 1)});
} else {
selectedItems = selectedItems.concat(item);
this.setState({ selectedItems: selectedItems });
}
};
render() {
const { categories } = this.props;
const { selectedItems } = this.state;
return (
<Content>
{categories.map(item => (
<label key={item.name}>
{item.name}
<Checkbox
name={item.name}
checked={selectedItems.includes(item.name)}
onChange={this.handleCheckbox}
/>
</label>
))}
</Content>
);
}
}
note: sorry for a very bad example of the code, I am still kind of new in react. However if you have any other tips, please advise.