1

I realise it's probably not even React issue and it's just me being confused beginner, but I'll ask question here anyway because I think I'm not understanding something.

I want to create a function that plays sound onClick event that's gonna be reusable.

Let's say I've got 2 audio tags in the render:

<audio ref="jammed" src={jammedSound}></audio>
<audio ref="budge" src={budgeSound}></audio>

and the function itself looks like this:

playSound(soundName){
  this.refs.soundName.play();
}

And it just won't work when I pass playSound('jammed') or playSound('budge'), I was trying to turn it to string in act of desperation, I was using curly brackets and brackets on soundName, nothing. I know it's probably JS issue I'm not understanding, I will be grateful for help

Chris
  • 57,622
  • 19
  • 111
  • 137

2 Answers2

1

Correct syntax would be

this.refs[soundName].play()

Not sure about React though.

More info : https://www.w3schools.com/js/js_properties.asp

Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
0

Please note that using string literals as refs is deprecated.

Instead, use functional refs:

<audio ref={(el) => this.jammedRef = el} src={jammedSound}></audio>
<audio ref={(el) => this.budgeRef = el} src={budgeSound}></audio>

and the function itself looks like this:

playSound(soundName){
  this[`${soundName}Ref`].play();
}
Chris
  • 57,622
  • 19
  • 111
  • 137