Issue
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).
.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.
Solution
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
Answered By - Catalin Bora
Answer Checked By - - Marie Seifert (ReactFix Admin)