What is the best way to change the heading text and color in React based on the time of day when calling a function?

I want to dynamically change the text and color of my h1 heading based on the time of day.
I'm encountering an error with my current code: "Cannot set property 'innerText' of null".
I've tried to figure out how to incorporate a function in the render section, but haven't had any luck.
This is what my code looks like:

import React from "react";
import ReactDOM from "react-dom";

const morning = { color: "blue" };
const afternoon = { color: "green" };
const night = { color: "grey" };
const date = new Date();
const currentHour = date.getHours();

function sayHello() {
  const heading = document.querySelector("h1");
  if (currentHour < 12) {
    heading.innerText = "Good Morning!";
    heading.style.color = morning;
  } else if (currentHour > 12 && currentHour < 18) {
    heading.innerText = "Good Afternoon!";
    heading.style.color = afternoon;
  } else {
    heading.innerText = "Good Night!";
    heading.style.color = night;
  }
}

ReactDOM.render(
  <h1 className="heading">{sayHello()}</h1>,
  document.getElementById("root")
);

Answer №1

Give this approach a try, it should work for you. You've defined a function but forgot to call it as well. Here's an alternative way to execute the code provided above.

import React from "react";
import ReactDOM from "react-dom";

// Set up time variable 
const time = new Date().getHours();
let greeting = "";

// Define color variable
let colorStyle = {
color: ""
};

// Implementing if/else statements
if (time <= 12) {
greeting = "Good Morning";
colorStyle.color = "blue";
} else if (time > 12 && time < 18) {
   greeting = "Good Afternoon";
   colorStyle.color = "green";
} else {
  greeting = "Good Night"; 
  colorStyle.color = "gray";
}

ReactDOM.render(
 <h1 className="heading" style={colorStyle}>
   {greeting}!
 </h1>,
 document.getElementById("root")
 );

Answer №2

This code snippet demonstrates a basic usage of React. To display a different greeting based on the time of day, you can follow this structure:

import React from "react";
import ReactDOM from "react-dom";

function Greeting() {
  const currentHour = new Date().getHours();
  
  // Determine the color and text for the greeting based on the current hour
  const [color, message] = 
    currentHour < 12 ? ["blue", "Good Morning!"] : 
    currentHour >= 12 && currentHour < 18 ? ["green", "Good Afternoon!"] :
    ["grey", "Good Night!"];

  return (
    <h1 style={{color}}>
      {message}
    </h1>
  )
}

ReactDOM.render(
  <Greeting />,
  document.getElementById("root")
);

Answer №3

I am a big fan of utilizing the useState and useEffect hooks in my projects.

Check out this example on CodeSandbox for more details!

import React, { useState, useEffect } from "react";

const morning = { color: "blue" };
const afternoon = { color: "green" };
const night = { color: "grey" };

const SayHello = () => {
  const [helloText, setHelloText] = useState("");
  const [helloTextColor, setHelloTextColor] = useState("");

  useEffect(() => {
    const date = new Date();
    const currentHour = date.getHours();
    if (currentHour < 12) {
      setHelloText("Good Morning!");
      setHelloTextColor(morning);
    } else if (currentHour > 12 && currentHour < 18) {
      setHelloText("Good Afternoon!");
      setHelloTextColor(afternoon);
    } else {
      setHelloText("Good Night!");
      setHelloTextColor(night);
    }
  }, []);
  return <div style={{ color: helloTextColor }}>{helloText}</div>;
};

export default SayHello;

Answer №4

When working with scripts, don't forget to utilize the Set Time Interval function to run your code at specified intervals, such as every minute. This allows you to continuously monitor and update your application state based on time intervals.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging GridFS-Stream to transfer image files to the Front-End React.js via Axios - Encoding chunks into base64 strings

I have managed to successfully upload my image file to MongoDB using Multer and Multer-Gridfs-Storage, however, I am encountering difficulties when trying to retrieve it. After attempting to retrieve the data with GridFS-Stream, I encountered a similar is ...

How to empty an array once all its elements have been displayed

My query pertains specifically to Angular/Typescript. I have an array containing elements that I am displaying on an HTML page, but the code is not finalized yet. Here is an excerpt: Typescript import { Component, Input, NgZone, OnInit } from '@angul ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

Stacking SVG elements can lead to distortion effects

Currently experimenting with the innovative SVG stacking method to integrate multiple icons into a single file, reducing the browser's HTTP requests. The details of this technique can be found in depth here. In essence, it involves placing numerous S ...

Looking for assistance in streamlining JavaScript for loops?

I am currently working on a project involving a random image generator that displays images across up to 8 rows, with a maximum of 240 images in total. My current approach involves using the same loop structure to output the images repeatedly: var inden ...

Error: The function getOrders is not defined in the customerFactory

Throughout my third attempt at learning AngularJS, I've hit a roadblock. I could really use some assistance as I keep encountering the error TypeError: customerFactory.getOrders is not a function. Despite thoroughly checking for typos, I haven't ...

What is the functionality of an Angular service that retrieves an

It appears that Angularjs services are constructed by passing in a Contructor function: app.service('serviceName', function(){ this.var1 = 'foo'; this.method1 = function(){ } }); Angular executes this function using the new ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

Ensuring draggable div remains fixed while scrolling through the page

I am currently working on creating a draggable menu for my website. The menu is functional and can be moved around the page as intended. However, I have encountered an issue where the menu disappears when scrolling down the page due to its position attrib ...

Retrieve Latitude and Longitude by clicking using JavaScript

When I click on the map, I want to retrieve the latitude and longitude coordinates and display them in an alert. Here is the code I have: <!DOCTYPE html> <html> <body> <div id="googleMap" style="width:100%;height:400px;"></div&g ...

Capacitor implementation of NextJS Server-Side Rendering

We are currently using Next.js with server-side rendering (SSR) and we are looking to integrate Capacitor.js into our app in order to make it compatible with both Android and iOS devices. However, it seems that this integration is only possible with static ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

What is the best way to navigate through the underlying MatDialog while the MatSelect is active?

When attempting to customize the scroll behavior of a MatSelect in a regular page, I discovered that using the MAT_SELECT_SCROLL_STRATEGY injection token with the NoopScrollStrategy allows for scrolling the underlying page while keeping the MatSelect stati ...

Apply a CSS class to the selected radio button when retrieving row data from the table

How can I dynamically add a CSS class to a snippet of code when a radio button is selected? Here's the jQuery Snippet: $(document).ready(function (){ $("input:radio").click(function () { if ($(this).is(":checked")) { var empid ...

How can we retrieve the clicked object in a done/fail function when using jQuery for an ajax request?

I am facing an issue with a simple ajax query that is triggered for every item of a class using the .click() event. The problem arises when trying to identify the clicked element in order to properly remove the m_action class in the .done() function. Desp ...

I am looking to remove the target attribute from an anchor tag if it does not have a value assigned

To ensure W3C validation, I must remove the target attribute from all anchors where the target value is null. Here is the code snippet inside the body: <div> <a href="#" target="">home empty</a> <a href="#" target="blank">home&l ...

Show a single jQuery Validation error

I am struggling with displaying an error message at the top if validation fails, without using the errorPlacement option. Instead, I want to showcase the message in a Bootstrap alert box. Below is the HTML code snippet: <form method="POST" action="/ro ...

Modifying the disabled attribute of an input tag upon button click in Angular 2

I am currently working on a function in Angular 2 where I want to toggle the disabled attribute of an input tag upon button click. Right now, I can disable it once but I am looking to make it switch back and forth dynamically. Below is the HTML template c ...