Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  145] [ 7]  / answers: 1 / hits: 15423  / 4 Years ago, thu, october 8, 2020, 12:00:00

I wanted to change the color of the heading during specific times of the day.(e.g At night blue, in the morning green...)
For this I'm trying to use inline-css(inside js file).


My css file:


.heading {
font-size: 50px;
font-weight: bold;
border-bottom: 5px solid black;
}

My js file:


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

const root = document.getElementById("root");

const curretnTime = new Date().getHours();

if (curretnTime < 12 && curretnTime >= 0) {
ReactDOM.render(
<div>
<h1 className="heading">Good Morning</h1>
</div>,
root
);
} else if (curretnTime >= 12 && curretnTime <= 18) {
ReactDOM.render(
<div>
<h1>Good Afternoon</h1>
</div>,
root
);
} else {
ReactDOM.render(
<div>
<h1>Good Evening</h1>
</div>,
root
);
}

I know it is pretty easy question to ask, but any answer would be helpful. Thank you.


More From » html

 Answers
20

You should use inline styles, like:


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

const root = document.getElementById("root");

const curretnTime = new Date().getHours();

let timeOfDay = 'evening'; // not used

let timeOfDayColor = 'blue';
let timeOfDayMessage = 'Good Evening';

if (curretnTime < 12 && curretnTime >= 0) {
timeOfDay = 'morning';

timeOfDayColor = 'green';
timeOfDayMessage = 'Good Morning';

} else if (curretnTime >= 12 && curretnTime <= 18) {
timeOfDay = 'afternoon';

timeOfDayColor = 'purple';
timeOfDayMessage = 'Good Afternoon';
}

ReactDOM.render(
<div>
<h1 className="heading" style={{backgroundColor: timeOfDayColor}} >{timeOfDayMessage}</h1>
</div>,
root
);

The style={{backgroundColor: timeOfDayColor}} is your inline style that overrides the CSS style : https://www.w3schools.com/react/react_css.asp


However, you should really use components and not have all the code in the ReactDOM.render method. Maybe try a react tutorial first: https://reactjs.org/tutorial/tutorial.html


[#50607] Thursday, September 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loric

Total Points: 110
Total Questions: 96
Total Answers: 91

Location: Estonia
Member since Wed, Jun 8, 2022
2 Years ago
;