How To Handle Conditional Styling In ReactJS

Introduction

This article will guide you on how to handle conditional styling in your react js application. In simple terms, how you will change your CSS style based on a given condition. So let's start and see.

How to implement

Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code).

Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.

Code

import logo from './logo.svg';
import './App.css'; 
function App() {
  const objectStyle = {
    color: "white",
    backgroundColor: "#ac5353"
    padding: "10px"
  };
  const objectStyleValid = {
    color: "Red",
    backgroundColor: "#bc3553",
    padding: "10px"
  };
  const isValid = true;
  return (
   <div>
      <h1 style={{color: "orange"}}>Welcome to rect js application</h1>
      <h3 style={objectStyle}> Styling using JS Object</h3>
      <h4 className="headerStyle">Styling using CSS</h4> 
      <h4 style={isValid ? objectStyle : objectStyleValid}>Conditional Styling using CSS</h4>
    </div>
  );
}
export default App;

Update isValid value as true and run the app. We can see once “isValid” value true then “objectStyleValid” is getting apply.

How to handle conditional Styling in React JS

Update isValid value as false and run the app. We can see once “isValid” value is false then “objectStyle” is getting apply.

How to handle conditional Styling in React JS

Summary

Today we saw, how we can apply CSS style in our react js app based on a condition. Try it for your project. Hopefully, this will help you.

Thank you.