In ReactJS, To Display Personalized Greeting message (like “Good Morning”, “Good Afternoon” ) based on the current time, we need to follow the following code.
import React, { useEffect, useState } from 'react';
import { Typography } from '@mui/material';
const Greeting = ({ user }) => {
const [greeting, setGreeting] = useState('');
const [color, setColor] = useState('');
const updateGreeting = () => {
const hour = new Date().getHours();
if (hour < 12) {
setGreeting('Good Morning');
setColor('#FFA726');
} else if (hour < 17) {
setGreeting('Good Afternoon');
setColor('#29B6F6');
} else if (hour < 20) {
setGreeting('Good Evening');
setColor('#9AB7BC');
} else {
setGreeting('Good Night');
setColor('#0FFDE4');
}
};
useEffect(() => {
updateGreeting();
const interval = setInterval(updateGreeting, 60 * 1000);
return () => clearInterval(interval);
}, []);
return (
<Typography variant="h6">
<span style={{ color, fontWeight: 500 }}>{greeting}</span>{' '}
<span>{user.name || user.role}</span>
</Typography>
);
};
export default Greeting;
const [greeting, setGreeting] = useState(”) ==> This holds the current Greeting string (like “Good Morning”, “Good Afternoon” ).
const [color, setColor] = useState(”) ==> This holds the current color for the Greeting Text.
const hour = new Date().getHours() ==> Gives current hour. Based on the current hour, it will compare with 12, 17, 20 and sets different greeting message and associated color.
useEffect() ==> For the first render calls updateGreeting(), and displays the Greeting message. Then we used setInterval(updateGreeting, 60 * 1000), to update the Greeting message for every 1 minute. Finally this line return () => clearInterval(interval), cleans up the interval when the component unmounts to prevent the memory leaks.