React Drum Machine - accessing children props

I’m making Drum Maching on React. Link - https://codepen.io/VasV/pen/abOwEwM?editors=0110
Trying to complete step 6 " When I press the trigger key associated with each .drum-pad, the audio clip contained in its child audio element should be triggered".
To make this happen I created handleKeyPress in Display class. The problem appears when I’m trying to access the components of children (Buttons): “source” which contains the URL of the sound and “text” which contains key name. I’d like to create a 2D array with text and source e.g [[‘Q’, ‘clap,mp3’], [W: ‘drum.mp3’]] and then iterate through it on eact key press. I’d like to create it iterating through props of each Button.
So handleKeyPress should be something like this:

 handleKeyPress(e) {
    let arr = [];
    let key = e.key.toUpperCase();
   /* here I somehow access props of Buttons, iterate through them (forEach or something similar)  and my arr looks like [['Q', 'clap,mp3'], [W: 'drum.mp3']] How can I do it? */
    for (let a = 0; a<arr.length; a++) {
	if (arr[a][0] == key) {
             let x = document.getElementById(key); 
             return x.play();
       }
}
}

Of course, I can hardcode the array but what if I want to add some more buttons?

@VasV what you should do is have them all in objects in the array and the map the buttons out this way you will have access to the array of objects and not have a load of hard coded buttons, this way you can add as many buttons as you like, so something like this


const arrayOfKeys = [
{   text: 'Q', source="http://sound.constantvzw.org/OpenSound/SAMPLES_ET_SONS_DIVERS/downloads/EMU%20E-Drum/Clap.wav"},
//and the rest of keys...
]
//or you could have this in state which
// is probably better idea if you want to use it in other functions too
// then map over it to create array of buttons


//then display the buttons
 render() { 

const buttons = arrayOfKeys.map(key => {
return <Button text={key.text} source={key.source} />
})

   return (
      <div id='display'>{buttons}</div>
    )  }

hope this makes sense.

1 Like

no need to loop over them as it goes…


    
 handleKeyPress(e) {
    let key = e.key.toUpperCase()
     let x = document.getElementById(key); 
      x.play();
    
  }