I’m working on the Drum Machine, one of the front end projects. on my best attempt, I have been able to make each button play a sound at a click. However, I got it to work by setting a state property to the id of each button inside the click handler so it’s updated to the id of the newly clicked button. So the problem is, it doesn’t update the state at the first click of another button, thereby playing the same sound once more.
Thanks a lot for your quick response. It’s working very well now. I appreciate your help.
Just another question, is my use of ref correct or the best way to use it in this case. I was wondering if there’s a away I could make the references shorter and compact rather referencing each element using a separate code.
Could you help me with some hints on this one? Upon pressing a button, a text for the triggered audio should be displayed in another element. And I have this element as a seperate component. So I don’t know how I may tie thi s component to the event that triggers the audio. thank you
Create state inside DrumMachine for the display name.
Create a function inside DrumMachine that sets the display name state.
Pass down the function which sets the state from DrumMachine as a prop to DrumPads. Call it inside DrumPads and pass it the value.
Pass down the display name state from DrumMachine, as a prop, to Display and then down to Title. Use the prop inside Title.
I’m not sure I can really explain it better than that without posting some code. I would suggest you read the React docs on Lifting State Up and see if you can make sense of it with the explanation I gave.
I understood your explanation to an extent but find it diffult it to implement from a certain point. I understand I have to set the display name in the DrumMachine using the function. I’m not sure what to set it to.
Here is my codepen: https://codepen.io/idrisishola/pen/yLvwbbZ
After that you now have access to this.props.displayName() inside DrumPads. You can call that function before the switch and pass it the name to set.
What you use for the name (the value you are going to pass to the displayName function) is up to you. But one option is to use the id on the button (the click target) event.target.id, you might split it on - and then join it back on a space.
If you want the Title component to display the name you have to pass it down one more time from Display to Title
Here is a simple example that shows the basic idea.