Showing Greeting Message using ReactJS

In ReactJS, To Display Personalized Greeting message (like “Good Morning”, “Good Afternoon” ) based on the current time, we need to follow the following code.

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.


Discover more from Learners Store

Subscribe to get the latest posts sent to your email.

One thought on “Showing Greeting Message using ReactJS”

Leave a comment