This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
Hi all, not really sure if this is the right sub but I'm stuck and don't really know where to turn.
I'm implementing a way to make a list from the user input and would like to add a button to delete the corresponding array. I can Add the button no problem (The Button is a component of it's own that's why it's a <Button /> element) but on the onClick I can't get it to work.
I'm trying to get the corresponding array index deleted with a click on the button. However, it doesn't work.
My code the following:
//The hooks for this code
`const [songsArray, updateSongsArray] = useState([])
const [newSong, setNewSong] = useState(''
)`
//function to make the initial songsArray
`function pushToSetlist(e){
e.preventDefault()
updateSongsArray((songsArray) =>[...songsArray, (newSong)])
setNewSong('')
}
`
//the jsx that implements the array.map on the page
`<ol>
{songsArray.map((songArray, index) =>{
return
<li key={index}>{songArray}
<Buttontype="button"onClick={() =>{songArray.splice(index, 1, 0)}}buttonText="X"/></li>})}
</ol>
`
If anyone could helpt me, or point me in the right direction I would be grateful.
Solved:
For some reason the .splice method does not agree with useState and the slice method is encouraged. I don't fully understand WHY this works though, so if anyone can elaborate I would appreciate it.
` function deleteButtonHandler(index) {
if (songsArray.length === 1 && index === 0) {
updateSongsArray([])
} else {
updateSongsArray([...songsArray.slice(0, index), ...songsArray.slice(index 1)])
}
}
`
`{ (songsArray.length >= 1) ?
songsArray.map((songArray, index) => {
console.log(index)
return <li>{songArray}
<Button
type="button"
onClick={() => {deleteButtonHandler(index)}}
buttonText="X"
/>
</li>
})
:
<li>There are no songs yet</li>
}
`
Subreddit
Post Details
- Posted
- 2 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/learnprogra...