React - How to play sounds?

React - How to play sounds?
0

#1

Does anyone know how to play Audio files from React?
The HTML5 audio tag doesn’t seem to work in JSX and I can’t find another solution. I’m trying to avoid interacting with the DOM directly if possible.

Thanks


Drum Machine - Audio Element?
#2

Also tried:
const sounds = {
green: new Audio(“https://s3.amazonaws.com/freecodecamp/simonSound1.mp3”),
blue: new Audio(‘https://s3.amazonaws.com/freecodecamp/simonSound2.mp3’),
pink: new Audio(‘https://s3.amazonaws.com/freecodecamp/simonSound3.mp3’),
yellow: new Audio(‘https://s3.amazonaws.com/freecodecamp/simonSound4.mp3’)
}
this.handleClick(color) => sounds[color].play

Which plays the sound, but totally destroys the rest of my game logic (side effects)


#3

I came up with a solution using refs in the end. It doesn’t feel quite right, but it’s better than nothing.