DEV Community

Himanshupal0001
Himanshupal0001

Posted on

1

Add dynamic class in react

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

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay