I have this component which requires user to select programs (all and/or single). After selecting a program, user can choose to add more programs by clicking on "Add another program" button at the end. Whatever I select on first box is displaying with the proper programs that I selected. However, when I go to second box and select program again, whatever I select on the second box is also updating the first box.
Can someone please help? I got most of the code written down:
this.state = {
programs: [],
programCheckedList: [],
programSelected: false
};
handleSelectProgram = e => {
const { checked } = e.target;
let collection = [];
if (checked) {
collection = this.handleGetAllPrograms();
}
this.setState({
programCheckedList: collection,
programSelected: checked
});
};
handleGetAllPrograms = () => {
const { programs } = this.state;
const collection = [];
for (const prog of programs) {
collection.push(prog.programId);
}
return collection;
};
handleProgramCheckbox = e => {
const { value, checked } = e.target;
if (checked) {
const collection = this.handleGetAllPrograms();
this.setState(prevState => ({
programCheckedList: [...prevState.programCheckedList, value * 1],
programSelected: collection.length === prevState.programCheckedList.length + 1
}));
} else {
this.setState(prevState => ({
programCheckedList: prevState.programCheckedList.filter(item => item != value),
programSelected: false
}));
}
};
render() {
return (
<label className="container select-all">
<input
type="checkbox"
id="selectAllPrograms"
checked={programSelected}
onClick={this.handleSelectProgram}
/>
<span class="checkmark" />
<p>
<strong>
All programs
</strong>
</p>
</label>
<hr/>
{_.map(programs, (program, pos) => {
const { programId, programDescription, programName } = program;
return (
<div className="programs-list" key={pos}>
<label className="container">
<input
type="checkbox"
id={`program_${programId}`}
name={`${programDescription} (${programName})`}
value={programId}
checked={programCheckedList.includes(programId)}
onChange={this.handleProgramCheckbox}
/>
<span class="checkmark" />
<p>{programName}</p>
</label>
</div>
);
})}
)
}
Desired output that I am looking for:
Box 1: program 1 selected
Box 2: program 1 and 2 selected
Box 3: all programs selected
Aucun commentaire:
Enregistrer un commentaire