Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing currentTime using React Component State

Heres a link to the sandbox. I'm looking for the best way to manipulate a <video> element's currentTime. In my sandbox I've been able to do that by having a button call a function seek() which changes the state of video, a reference to document.getElementById('video-player'), see below.

export default class VideoPlayer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      source: props.source,
      timestamp: props.timestamp
    };
  }

  componentDidMount() {
    this.setState({ video: document.getElementById('video-player') })
  }

  componentDidUpdate(prevProps) {
    if (this.props !== prevProps) {
      this.setState(
        { timestamp: this.props.timestamp }, 
        () => { this.seek() }
      );
    }
  }

  seek = () => {
    console.log(this.state.timestamp)
    //works
    this.state.video.currentTime = 1;
    //doesn't work
    //this.state.video.currentTime = this.state.timestamp;
  }

  render() {
    return (
      <div>
        <video 
          id='video-player'
          height='200px'
          src={this.state.source} 
          type='video/mp4'
          controls>
        </video>
        {/* I don't want this button. I want skip from the outside */}
        <button onClick={this.seek}>Skip Inside Component</button>
      </div>
    );
  }
}

The thing I can't figure out is that I can only manage to change currentTime inside the component because for whatever reason, I can't assign this.state.timestamp to the currentTime of my <video> reference (this.state.video.currentTime).

Ultimately the component should receive props.timestamp, provided by Redux, call seek() inside <VideoPlayer /> whenever Redux's state changes, and set the video's currentTime to this.state.timestamp.

Let me know if you guys need any more details. Thanks in advance!

EDIT: The above has been answered but I'm still having an issue. The sandbox I shared and just fixed still won't work in my rails project though. I had a feeling it wouldn't. When one of the three buttons in App.js is clicked, the state changes in Redux and is successfully received by <VideoPlayer>. This is confirmed by my console.log inside of seek() which returns the corresponding button's value to the console. However, the video's currentTime still doesn't change. Any ideas here?

like image 907
Gregory Jaros Avatar asked Jan 01 '26 21:01

Gregory Jaros


1 Answers

In mapStateToProps your state is the timestamp, and not state.timestampReducer.

This should work:

const mapStateToProps = (state) => {
  return {
    timestamp: state
  }
};
like image 177
Sagiv b.g Avatar answered Jan 03 '26 10:01

Sagiv b.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!