I am using react-timer-hook to set up a stopwatch for my React Application. So I got a Timer.js file where this stopwatch is working with a start and pause button. I am calling the component in App.js so the timer shows up on all pages. My next step is to set up that start functionality in a different component named Start.js (and later on the pause in the final page), but I can't figure out how I can pass it to this component.
This is my App.js:
function App() {
return (
<Router>
<div className="App">
<Timer/>
<Routes>
<Route path="/" element={ <Start /> }></Route>
// Other routes
</Routes>
</div>
</Router>
);
}
export default App;
Timer.js file:
function MyTimer({ expiryTimestamp }) {
const {
seconds,
minutes,
start,
pause,
} = useStopwatch({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
return (
<div className="timer">
<div className='timer-inside' >
<span>{minutes < '10' ? '0' + minutes : minutes}</span>:<span>{seconds < '10' ? '0' + seconds : seconds}</span>
</div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
</div>
);
}
export default function App() {
return (
<div>
<MyTimer/>
</div>
);
}
So basically i want the <button onClick={start}>Start</button>
snippet to work in a file called Start.js, instead of the Timer.js itself.
If you want to render the Start component as a children of Timer, you can pass the start function received from the useStopwatch hook like
<Start onClick={start} />
And inside the Start
<button onClick={onClick}>Start</button>
But, if you want to render it on App, you need to call the hook on App and pass what you need on the components you need:
function App() {
const timer = useStopwatch({ onExpire: () => console.warn('onExpire called') });
return (
<Router>
<div className="App">
<Timer data={timer} />
<Routes>
<Route path="/" element={ <Start data={timer} /> } />
// Other routes
</Routes>
</div>
</Router>
);
}
export default App;
So in both components will have same data property.
Hope it helps!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments