Add dynamic class in react
Himanshupal0001

Himanshupal0001 @himanshupal0001

About: Full stack web Dev. Like to teach and learn. Open for free lance and open source projects.

Location:
DXB
Joined:
Nov 21, 2021

Add dynamic class in react

Publish Date: Jan 3 '23
2 0

Today we gonna see how to add classes dynamically in jsx to change design.

Suppose we have below line of code

-- js
import React from "react";
import "./App.css";

function App() {
const row=[
{status: 'approved'},
{status: 'pending'},
{status: 'approved'},
{status: 'pending'},
]
  return (
    <div className="App">
    <div className='list'>
    {row.map((item) => (
     <span className='listbatch'>
     {item.status}
    </span>
    ))}
    </div>
    </div>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

You'll get something like this

Image description

Now you need just add class in literal and add state of that class

function App() {
const row=[
{status: 'approved'},
{status: 'pending'},
{status: 'approved'},
{status: 'pending'},
]
  return (
    <div className="App">
    <div className='list'>
    {row.map((item) => (
     <span className={`listbatch ${item.status}`}>
     {item.status}
    </span>
    ))}
    </div>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Image description

Below is the css file

.list{
    display: flex;
    flex-direction: column;
    height: 20vh;
    width: 20vw;
    box-shadow:2px 4px 10px 1px rgba(218,218,218,0.478); 
    border-radius: .5rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(0%, -50%);
    padding: 10px;
}

.listbatch{
padding: 5px;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
}

.approved{
background-color: green;
color: white;
}

.pending{
background-color: yellow;
color: black;
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment