When a new drum is added to the array of drums in setDrums
each drum component is displayed, the user can give the drum a name, how do I add the name
to the drum in the array drums
?
I can logout the drum id, but how do I find that drum in the array and only update that drum with the name the user entered?
https://codesandbox.io/s/amazing-dan-dsudq?file=/src/index.js:0-1371
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const rootElement = document.getElementById("root");
const Drum = ({ id, count, remove, editName, name }) => {
const [sounds, setSounds] = useState(count);
useEffect(() => {
if (sounds > 0)
setTimeout(() => {
console.log("Playing sound");
setSounds(sounds - 1);
}, 1000);
}, [sounds]);
return (
<div>
<p>Drum #{id}</p>
<p>Drum Name {name}</p>
<p>Remaining sounds: {sounds}</p>
<label>
Drum Name <input type="text" onChange={editName} />
</label>
<br />
<button onClick={remove}>Delete drum #{id}</button>
</div>
);
};
const App = () => {
const [drums, setDrums] = useState([]);
const [nextId, setNextId] = useState(0);
return (
<div>
{drums.map(drum => (
<Drum
key={drum.id}
id={drum.id}
count={drum.count}
remove={() => setDrums(drums.filter(other => drum.id !== other.id))}
editName={() => console.log(drum.id)} // <== how to save the entered name to setDrums?
name={drum.name}
/>
))}
<button
onClick={() => {
setDrums([
...drums,
{ id: nextId, count: Math.floor(Math.random() * 100) }
]);
setNextId(nextId + 1);
}}
>
Add drum
</button>
</div>
);
};
ReactDOM.render(<App />, rootElement);