I have a list of checkboxes and when one it selected, I want the associated ID to be added to a state object and when its unchecked, the ID should be removed from the state object.
Currently, the state object only updates when a second checkbox is selected (and state only contains the first checkbox) -- aka its always 1 checkbox behind. Its then the opposite when unchecking -- if 3 boxes are checked, state shows 4 boxes selected.
I'm a super new dev so I'm sure this is incredibly simple, any help would be much appreciated :)
const [checkedState, setCheckedState] = useState(new Array(20).fill(false));
const [checkedPlaylists, setCheckedPlaylists] = useState({});
const handleChange = (position, id) => {
const updatedCheckedState = checkedState.map((item, index) =>
index === position ? !item : item
);
setCheckedState(updatedCheckedState);
if (checkedState[position] === false) {
setCheckedPlaylists(prev => {
return {
...prev,
[position]: id
}
})
} else {
setCheckedPlaylists(prev => {
delete checkedPlaylists[position]
return { ...prev }
})
}
}
Here's the jsx
return (
<>
<h3>Select Playlists</h3>
<form onSubmit={handleSubmit}>
<ul className='playlists-list' style=>
{playlists?.items.map((playlist, index) => {
return (
<li key={index}>
<div className='playlists-list-item'>
<input
type='checkbox'
id={`custom-checkbox-${index}`}
name={playlist.name}
value={playlist.name}
checked={checkedState[index]}
onChange={() => handleChange(index, playlist.id)}
/>
<label htmlFor={`custom-checkbox-${index}`}>{playlist.name}</label>
</div>
</li>
)
})}
</ul>
<div>
<button className='submit-btn' type='submit'>Submit</button>
</div>
</form>
<TopSongs playlists={playlists} />
</>
)
Aucun commentaire:
Enregistrer un commentaire