0

I'm trying to change a class name dynamically in react.

I am importing the classes from a related css file like this:

import classes from "./Board.module.css";

And in my Board component, I want to return a classname based on something I generate.

It can be "card" "card activate " "card disable", and I have 3 classes in my css file

.card {
    do card something
}

.card.activate {
    do card  activate something
}

.card.disable {
    do card disable something
}

How can I do it because concatenating doesn't seem to be working

Edit: I am trying to to this:

import  "./Board.module.css"

const Card = (props) => {
  const itemClass =
    "card" + (props.item.stat ? " active " + props.item.stat : "");
  return (
    <div className={itemClass} onClick={() => props.clickHandler(props.id)}>
      <label>{props.item.content}</label>
    </div>
  );
};

export default Card;

and the CSS is :

.card.wrong{
    background-color: red;

}
.card.correct{
    background-color: green;
}
.card.active{
    transform: rotateY(0);
}

I am doing so that every time I click a card, I change its class name to active and something and based on that I do a color but the class is undefined so I don't know what to do

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BoazBitt
  • 19
  • 3
  • Does this answer your question? [React Js conditionally applying class attributes](https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes) – Ergis Dec 03 '22 at 16:06

1 Answers1

0

Have you tried looking the element in inspect mode to see whether the classes are getting attached without spaces?

Eg. card active is getting applied as cardactive.

However, here's how you'd do it :

// Board.module.css
.card{
do card somthing

}
.card.activate{
do card  activate somthing

}
.card.disable{
do card disable somthing

}

Here's a snippet of the component which uses the classes dynamically. A dummy condition is used to simulate the truthy/falsy behavior that changes the class. Replace this using your custom logic.

Using string literals you can dynamically toggle between the classes as shown below:

import "./Board.module.css";

const MyComponent = () => {
const [condtion, setCondition] = useState(false); // this is the condition that toggles the class
return (
<>
 <span className={`card ${condition ? 'activate' : 'disable'}`}>Hello world</span>
</>

Note: the activate and disable class-Names are strings and not variables.

kanuos
  • 985
  • 9
  • 16