Azadeh :
I want to create a timer with a reset button. I must do this exercise in an initial code that is written by React. This is the initial code.
import React, {Component} from 'react';
import './Timer.css';
export class Timer extends Component {
render() {
return <div className="container">
<div className="timer">
</div>
<button>Reset Timer</button>
</div>;
}
}
I've tried two solution but each of them returned different error. Here is my first solution.(figure 1) figure 1
and the error is (figure 2) figure 2
and my second solution is this ... (figure 3) figure 3
import React, {Component} from 'react';
import './Timer.css';
const initialState = {
seconds: 0
}
export class Timer extends Component {
constructor(props) {
super(props);
this.state = initialState;
}
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
resetTimer() {
this.setState(initialState);
}
render() {
return <div className="container">
<div className="timer">
{this.state.seconds}
</div>
<button onClick = {this.resetTimer}>Reset Timer</button>
</div>;
}
}
and its error is that ... (figure 4) figure 4
How can I solve the problem of resetting the timer?
Reda.a :
The problem comes from the "this" scope.
Either you have to bind the function you're using in the class.
constructor( props ){
super( props );
this.resetTimer = this.resetTimer.bind(this);
}
A second option is to use arrow functions when you declare your functions in order to maintain the scope of "this" on the class.
resetTimer = () => {
this.setState(initialState);
}