React JS App – inline CSS for HTML, Dynamic Styling

Adding custom css to html elements inside react app. Updating the css styles dynamically based on conditions. Sample react app code based on css usage.

index.js

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

const today = new Date();
const time = today.getHours();
let msg;

const msgStyle = {
  color: "Red"
}

if(time<12){
  msg = "Good Morning";
  msgStyle.color = "Red";
}else if(time<18){
  msg = "Good Afternoon";
  msgStyle.color = "Green";
}else{
  msg = "Good Night";
  msgStyle.color = "Blue";
}

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

style.css

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

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>JSX</title>
    <link rel="stylesheet" href="styles.css" />
  </head>

  <body>
    <div id="root"></div>
    <script src="../src/index.js" type="text/JSX"></script>
  </body>
</html>

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *