snowflakekiller snowflakekiller - 2 months ago 14
React JSX Question

update component every second react

I have been playing around with React and have the following time component that just renders

Date.now()
to the screen:

import React, { Component } from 'react';

class TimeComponent extends Component {
constructor(props){
super(props);

this.state = { time: Date.now() };
}
render(){
return(
<div> { this.state.time } </div>
);
}
componentDidMount() {
console.log("TimeComponent Mounted...")
}
}

export default TimeComponent;


What would be the best way to get this component to update every second to re-draw the time from a React perspective?

Answer

this is react js website example :

var Timer = React.createClass({
  getInitialState: function() {
    return {secondsElapsed: 0};
  },
  tick: function() {
    this.setState({secondsElapsed: this.state.secondsElapsed + 1});
  },
  componentDidMount: function() {
    this.interval = setInterval(this.tick, 1000);
  },
  componentWillUnmount: function() {
    clearInterval(this.interval);
  },
  render: function() {
    return (
      <div>Seconds Elapsed: {this.state.secondsElapsed}</div>
    );
  }
});

ReactDOM.render(<Timer />, mountNode);
Comments