I am working on a project where I have 4 options, but I should only be able to select one option per screen. The option pushes an object with an id and a score (based on the screen) to an array in the state. So if I make one selection and change to another, I'd like to able to remove the previous object and append the new one in an array in the state (for each screen). I have script to append and remove the object if I'm clicking on the same option, but I'm not sure what I would do to replace the object with a new one if I make a selection then immediately go to another.
The array looks as follows:
scores: [
[{id: "G1", score: "4"}, {id: "B1", score: "3"}, {id: "O1", score: "2"}, {id: "R1", score: "1"}],
[{id: "B2", score: "4"}, {id: "G2", score: "3"}, {id: "R2", score: "1"}, {id: "O2", score: "4"}]
]
Here is the code I have now:
handleScore = (id, score, idx) => {
const {
statements,
scores
} = this.state;
if (statements[0][idx].isSelected) {
this.setState({
scores: scores.map((item, index) => index === 0 ? [...item, {
'id': id,
'score': score
}] : item)
});
} else {
this.setState({
scores: scores.map((item, index) => index === 0 ? item.filter(i => i.id !== item[0].id) : item)
});
}
}
and in the render method I have:
<div
className={`statement ${(this.state.statements[0][index].isSelected) ? 'selected' : ''}`} key={item.id} onClick={e => {
e.preventDefault();
this.handleScore(item.id, match.params.score, index)
}}>
<a href="#">{item.statement}</a>
</div>
Thank you in advance!