In this lesson, we will create event listeners for the play and pause events on an audio player element and use these listeners to update the value of a variable called
isPlaying that tracks the current state of the player (e.g., whether it is currently playing or paused). The event listeners, named
onPause, will be triggered when the user presses the play or pause button on the audio player element itself, not on a custom play button that may have been created.
Instructor: [0:00] So far, what we have is working well, but we haven't mapped all of the audio elements states to the react app states. For example, when I press Play on the audio player, you'll notice that this state does not change. Let's go back to the MDN docs. [0:16] Down in the event section, we have the play event and the pause event. We can use the play event to set isPlaying to true, and we can use the pause event to set isPlaying to false.
[0:27] Back in the code, underneath onTimeUpdate, we'll type onPlay, and we'll just do a function in here, that's setIsPlayingToTrue. Then onPause we'll do the same thing and pass a function of setIsPlayingToFalse. Let's go back to the app, refresh. Now, if I press this Play button, the state will update.
[0:53] To summarize, we have just mapped the play and pause events to the react state. We added onPlay on the audio element and set isPlaying to true, and we took the pause and onPause on the audio element, we set isPlaying to false.