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:
jsximport 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:
-
It uses the
useStateHook to define a state variable namedcurrentDateTime, initialized with aDateobject representing the current date and time at the initial render. -
It creates a side effect using the
useEffectHook, which executes after the component renders. Within this side effect, it sets up an interval usingsetIntervalto update thecurrentDateTimestate every second. -
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. -
The
formatDatefunction accepts aDateobject as a parameter and returns a formatted string displaying the date and time. You can customize this function to meet your formatting requirements. -
Finally, the component returns a JSX element containing the current date and time. Whenever the
currentDateTimestate changes (every second), the component re-renders to display the latest time.