I'm new to react and I've been trying to create a countdown timer for chess using the library countdown-now. I currently have a clock component that displays the time. I don't know how to call the start and stop function.
Here's a link to the library: https://www.npmjs.com/package/react-countdown-now#api-reference
My code for the Clock component:
function Clock({ time }) {
return (
<div style={clockStyle}>
<Countdown
date={Date.now() + (time * 60000)}
intervalDelay={3}
zeroPadTime={2}
autoStart={false}
daysInHours
/>
</div>
);
}
In the parent component:
<Clock time={state.time} />
From the documentation:
The countdown component exposes a simple API through the getApi() function that can be accessed via component ref. It is also part (api) of the render props passed into renderer if needed.
And once we have access to the API:
start() Starts the countdown in case it is paused or needed when autoStart is set to false.
So first, we need to get access to the API (via ref)
export default class Clock extends React.Component {
render() {
const { refCallback, time } = this.props;
return (
<Countdown
// When the component mounts, this will
// call `refCallback` in the parent component,
// passing a reference to this `Countdown` component
ref={refCallback}
date={Date.now() + (time * 60000)}
intervalDelay={3}
zeroPadTime={2}
autoStart={false}
daysInHours
/>
);
}
}
Now we can access the API as described in the documentation.
class App extends React.Component {
clockRef = null;
constructor(props) {
super(props);
this.setClockRef = this.setClockRef.bind(this);
this.start = this.start.bind(this);
this.pause = this.pause.bind(this);
}
start() {
this.clockRef.start();
}
pause() {
this.clockRef.pause();
}
setClockRef(ref) {
// When the `Clock` (and subsequently `Countdown` mounts
// this will give us access to the API
this.clockRef = ref;
}
render() {
return (
<>
<button onClick={this.start}>Start Clock</button>
<button onClick={this.pause}>Pause Clock</button>
<Clock refCallback={this.setClockRef} time="100" />
</>
);
}
}
Clicking the start button will start the countdown, clicking the pause button will pause the countdown.