javascriptreactjsonkeypresshowler.js

How do i use OnKeypress to use my button depending the key pressed


Hi i want to reproduce a sound depending on the key pressed but how do i passed into my onkeypress? i reproduce the sound with howler and the i used a map function to reproduce and create a button for all the buttons but i dont know how to use it with a onkeypress, like i want it to change the button sound if i press another key like w,etc

//create an array for audioClips
const audioClips = [
{sound : bass, label: "BassDrum"},
{sound : hithat, label: "HitHat"},
{sound : ride, label: "Ride"},
{sound : snare, label: "Snare"},
{sound : splash, label: "Splash"},
{sound : tom, label: "Tom"},
]
class App extends Component {
SoundPlay = (src) => {
const sound = new Howl({
  src
});
sound.play();
}

RenderButtonAndSound = () => {
  return audioClips.map((soundObj,index) => {
    return(
      <button key={index}onKeyPress={() => this.SoundPlay(soundObj.sound)} onClick={() => 
 this.SoundPlay(soundObj.sound) }>
        {soundObj.label}
      </button>
    )
  });
  
 }

 render(){
Howler.volume(1.0)
return (
  <div className="App">
    <h2>
      My Virtual Drums
    </h2>
    {this.RenderButtonAndSound()}
  </div>
 );
 }
}

export default App;

Solution

  • Using the onKeyPress event, you can check the keys being entered.

       const keyboardEvents = (event) =>{
           console.log(event.key); // this will return string of key name like 'Enter'
           console.log(event.keyCode) //using keycode
    
      if (e.keyCode == 13) { //Press Enter
        this.SoundPlay(soundObj.sound)
      }
    
           //You can use If-Else or Switch statements to call different sound base on event.key
       }
    
    
    RenderButtonAndSound = () => {
      return audioClips.map((soundObj,index) => {
        return(
          <button key={index} onKeyPress={(e) => this.keyboardEvents(e)} onClick={() => 
     this.SoundPlay(soundObj.sound) }>
            {soundObj.label}
          </button>
        )
      });
      
     }