Creating a Toggle Button for Muting and Unmuting an Audio Element in React

InstructorLindsey Kopacz

Share this video with your friends

Send Tweet

We are creating a toggle button for muting and unmuting an audio element using React hooks useState and useRef. It destructures isMuted from the useState hook and sets the initial state to false.

The button's inner text is dependent on the state of isMuted, and a toggleMute function is created which sets isMuted to the opposite of its current state and also sets the audioRef.current.muted property to the opposite of isMuted.

A onVolumeChange function is added to the audio element that sets the isMuted state based on the value of audioRef.current.muted. This allows the isMuted state to change even when the mute button on the audio element itself is pressed.

Think about:

  • Why do we have to add onVolumeChange for instead of onMuted?
  • How can we use onVolumeChange to check for things being muted?