1
votes

I'm working on the freeCodeCamp drum machine project. When the user clicks the drum pad, I'd like a sound to play. Since the audio element isn't the real DOM element but a copy of it, to refer to it I need to use a ref (or at least I think that's why).

I followed the React doc instructions for using a ref in a function component, and I have a method handleClick that's triggered when you click a "drum pad" which I'd like to call audio.play(). However, when I click one of the drum pads, the app crashes with an error "audio.play is not a function." Is it a problem with the ref? Any suggestions appreciated.

Child component DrumPad.js:

const DrumPad = ({ id, letter, src }) => {

  let audio = React.createRef(); // <--

  const handleClick = () => { // <--
    audio.play();
  }

  return (
    <div
      className="drum-pad"
      id={id}
      onClick={handleClick}
    >
      <p>{letter}</p>
      <audio
        ref={audio} // <--
        id={letter}
        src={src}
      >
      </audio>
    </div>
  );
}

Parent App.js:

const sounds = [
  { id: 'snare', letter: 'Q', src: 'https://www.myinstants.com/media/sounds/snare.mp3' },
  // etc.
];

const App = () => {

  return (
    <div className="drum-machine">
      <div className="drum-pads">
        {sounds.map(sound => (
          <DrumPad
            id={sound.id}
            letter={sound.letter}
            src={sound.src}
          />
        ))}
      </div>
    </div>
  );
}
1

1 Answers

1
votes

The DOM node is actually store under the current key.

This should fix your problem:

const handleClick = () => { 
    audio.current.play();
}

React docs about createRef