I’m trying to figure out why the drum machine plays the same sound:
It plays the last item in the array every time.
I’m trying to figure out why the drum machine plays the same sound:
It plays the last item in the array every time.
First problem is that you don’t initialise the audio
variable with a keyword, so by doing this:
<audio
...
ref={ref => audio = ref}
>
</audio>
… it accidentally becomes a global variable (which is something you don’t want).
When you loop over your DrumPads, that variable gets overwritten every time, and at the end it has the value of the last element.
You can solve this relatively easy with useRef
:
const audio = React.useRef({})
You initialise it with an empty object, and when you loop over the pads, add a different property for each pad:
<audio
...
ref={ref => audio[props.name] = ref}
>
</audio>
In your click and keydown handlers, you can then access them with
audio[props.name].play()
I should add that I rarely used useRef
, so I’m not 100% confident if this is hacky or the way it should be. Works though.
Thank you for your help! It works now. I spent so much time trying to figure this out
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.