Using React Reference to play HTML audio functions resulting in undefined errors: 25+5 Clock


I am working on the React 25+5 clock.

In the JS code, on line 78, I have a functions to play the sound linked to the audio element on line 227 under the reference created on line 27.


On line 103, I have a setInterval function that runs and calls the playSound() function when the seconds hits zero.


    playSound() {
      this.soundRef.currentTime = 0


  start_stop() {
      Because refering to "this" in a setInterval will not refer to react component, I create a reference to React this and store it in self.
      let self = this
      // If clock is paused
      if (self.state.paused) {
        let tempIntervalID = setInterval(function () {
          if (self.state.status == "Session") {
            // Create a temp value for current time
            let newSessionTime = self.state.countSession;
            // subtract while seconds-1 >= 0
            if (newSessionTime-1 >= 0) {
            if (newSessionTime == 0) {
            console.log(newSessionTime, self.formatTime(newSessionTime))
            // Set the state of the component each interval loop.
            // Resets the value of the break timer.
            // Status is set to Break if clock hits zero
              countBreak: self.state.initalBreak * 60,
              countSession: newSessionTime,
              breakString: self.formatTime(self.state.initalBreak*60),
              sessionString: self.formatTime(newSessionTime),
              paused: false,
              intervalID: tempIntervalID,
              status: newSessionTime == 0 ? "Break" : "Session"
          } else if (self.state.status == "Break") {
            let newBreakTime = self.state.countBreak;
            if (newBreakTime-1 >= 0) {
            if (newBreakTime == 0) {
            console.log(newBreakTime, self.formatTime(newBreakTime))
            // Resets the seconds of the session. After the session subtracts, it will be left at zero. If this is the case, it wont loop through session again. So it must reset.
              countBreak: newBreakTime,
              breakString: self.formatTime(newBreakTime),
              paused: false,
              intervalID: tempIntervalID,
              status: newBreakTime == 0 ? "Session" : "Break",
              countSession: self.state.initalSession*60,
              sessionString: self.formatTime(self.state.initalSession*60),
        }, self.state.oneSecondMS);

However, playing the sound results in a error that the .play, .pause and other functions are undefined. Any ideas on why my React reference doesn’t follow this audio element properally?

because refs is an object with a key of current

Accessing Refs

When a ref is passed to an element in render , a reference to the node becomes accessible at the current attribute of the ref.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.