乐闻世界logo
搜索文章和话题

How to show time and date in realtime in React JS?

1个答案

1

In ReactJS, to display time and date in real-time, you can implement a component that uses state to store the current date and time and employs the setInterval method to periodically update this state. Below is a basic example of how to create such a component:

jsx
import React, { useState, useEffect } from 'react'; // Create a functional component const DateTimeDisplay = () => { // Use the useState Hook to initialize state const [currentDateTime, setCurrentDateTime] = useState(new Date()); useEffect(() => { // Set up an interval to update the current time every second const timer = setInterval(() => { setCurrentDateTime(new Date()); }, 1000); // Clear the timer when the component unmounts return () => { clearInterval(timer); }; }, []); // Format the date and time const formatDate = (date) => { // Adjust the format as needed return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`; }; return ( <div> <p>Current date and time:</p> <p>{formatDate(currentDateTime)}</p> </div> ); }; export default DateTimeDisplay;

In the above code, the DateTimeDisplay component accomplishes the following:

  1. It uses the useState Hook to define a state variable named currentDateTime, initialized with a Date object representing the current date and time at the initial render.

  2. It creates a side effect using the useEffect Hook, which executes after the component renders. Within this side effect, it sets up an interval using setInterval to update the currentDateTime state every second.

  3. Inside the return function of useEffect, it sets up a cleanup function that executes before the component unmounts to clear the previously set interval. This is a crucial step to prevent memory leaks.

  4. The formatDate function accepts a Date object as a parameter and returns a formatted string displaying the date and time. You can customize this function to meet your formatting requirements.

  5. Finally, the component returns a JSX element containing the current date and time. Whenever the currentDateTime state changes (every second), the component re-renders to display the latest time.

2024年6月29日 12:07 回复

你的答案