I am working on a stopwatch app using ReactJS and Electron. I have a Timer component, which keeps track of the time and displays the clock & controls.
The controls will be made up of three buttons: Play, Pause, and Stop. These Button components are completely unrelated to the Timer component.
My question is: if I have a handleStopClick()
function in the Timer component, how can I call it from the StopButton component?
Note: there is currently no Play/Pause functionality. The Timer simply starts when mounted and a single Stop button should clear it. I'll add the rest when I've sorted this out.
Here is Timer.jsx:
import '../assets/css/App.css';
import React, { Component } from 'react';
import PlayButton from './PlayButton'; // No function
import PauseButton from './PauseButton';
import StopButton from './StopButton';
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
isRunning: false,
secondsElapsed: 0
};
}
getHours() {
return ('0' + Math.floor(this.state.secondsElapsed / 3600)).slice(-2);
}
getMinutes() {
return ('0' + Math.floor(this.state.secondsElapsed / 60) % 60).slice(-2);
}
getSeconds() {
return ('0' + this.state.secondsElapsed % 60).slice(-2);
}
handleStopClick() {
clearInterval(this.incrementer);
}
componentDidMount() {
this.isRunning = true;
console.log(this.isRunning);
var _this = this; // reference to component instance
this.incrementer = setInterval( () => {
_this.setState({
secondsElapsed: (_this.state.secondsElapsed + 1)
});
}, 1000)
}
playOrPauseButton() {
if (this.isRunning) {return <PauseButton />}
else {return <PlayButton />}
}
render() {
return (
<div>
{this.playOrPauseButton()}
<StopButton /> <hr />
{this.getHours()} : {this.getMinutes()} : {this.getSeconds()}
</div>
);
}
}
export default Timer;
And StopButton.jsx:
import '../assets/css/App.css';
import React, { Component } from 'react';
import Timer from './Timer';
class StopButton extends Component {
handleClick () {
console.log('this is: ', this);
Timer.handleStopClick() // here's where I'd like to call Timer's function
}
render() {
return (
<button onClick={(e) => this.handleClick(e)}>
■
</button>
);
}
}
export default StopButton;