Search code examples
reactjscountdown

how to call onStart function in react-countdown?


<Countdown
    date={Date.now() + (n.duration)}
    ref={this.refCallback}
    autoStart={false}

    renderer={({ hours, minutes, seconds, completed }) => {
        if (completed) {
            // Render a completed state
            return <div>Times up</div>;
        } else {
            // Render a countdown
            return <h1 className="m-0 font-weight-bold">{hours}:{minutes}:{seconds}</h1>;
        }
    }}
/>

Here is documentation https://www.npmjs.com/package/react-countdown

Thanks.


Solution

  • You can check document api of library CountDown component. It provides method start here. You can call this.refCallback.start() in some where to start. Example:

    const Component =(props) => {
        const ref= useRef();
    
        const handleStart = (e) => {
            ref.current?.start();
        }
    
        const handlePause = (e) => {
            ref.current?.pause();
        }
    
        return <>
            <button onClick={handleStart}> Start </button>
            <button onClick={handlePause}> Pause </button>
            <Countdown
                date={Date.now() + (20000)}
                ref={ref}
                autoStart={false}
    
                renderer={({ hours, minutes, seconds, completed }) => {
                    if (completed) {
                        // Render a completed state
                        return <div>Times up</div>;
                    } else {
                        // Render a countdown
                        return <h1 className="m-0 font-weight-bold">{hours}:{minutes}:{seconds}</h1>;
                    }
                }}
            />
            </>
    }