This tutorial extends our React stopwatch to include lap timing functionality – a crucial feature for any serious timekeeping application. We'll leverage our knowledge of React state management, arrays, and conditional rendering to achieve this. This is part 3 of the Building a Stopwatch in React series.
Frequently Asked Questions (FAQs) about Adding Lap Logging to a React Stopwatch
Adding lap logging requires a function triggered by a "Lap" button. This function captures the stopwatch's current time and adds it to an array. The useState
hook manages this array.
const [laps, setLaps] = useState([]); const handleLap = () => { setLaps([...laps, currentTime]); };
Display lap times by mapping over the laps
array, rendering a component for each lap:
{laps.map((lap, index) => ( <p key={index}>Lap {index + 1}: {lap}</p> ))}
Improve readability by converting milliseconds to minutes, seconds, and milliseconds using a helper function:
const formatTime = (time) => { const minutes = Math.floor(time / 60000); const seconds = Math.floor((time - minutes * 60000) / 1000); const milliseconds = time - minutes * 60000 - seconds * 1000; return `${minutes}:${seconds}:${milliseconds}`; };
Resetting lap times involves clearing the laps
array:
const handleReset = () => { setLaps([]); // ...reset stopwatch... };
Accuracy is paramount. The lap logging function should be synchronous to avoid delays in capturing the current time.
Introduce a state variable to track whether the stopwatch is running:
const [isRunning, setIsRunning] = useState(false); // ...in the time increment function... if (isRunning) { // ...increment time... }
Preserve the current time when pausing; only reset it during a full reset.
Use localStorage
to store lap times, ensuring persistence even after page refreshes:
const handleLap = () => { const newLaps = [...laps, currentTime]; setLaps(newLaps); localStorage.setItem('laps', JSON.stringify(newLaps)); };
Use CSS media queries to adjust the layout and sizing for different viewport sizes:
@media (max-width: 600px) { .stopwatch { font-size: 20px; } .lap-logger { font-size: 16px; } }
The above is the detailed content of Watch: Adding a Lap Logger to a React Stopwatch. For more information, please follow other related articles on the PHP Chinese website!