Can we have two class attributes for a single div element separately?

Viewed 72

I am working on a React application. I want to have a div with a conditional class as shown below:

<div class="defaultClass1 defaultClass2" class = {player_color === 1? "bg-green" :"bg-opponent"}>
      <p>Body</p>
</div>

I find that, the class that is written second completely overrides the prev. So is there an easy way i can get the effect of both classes without repeating the default class inside the "bg-green" and "bg-opponent" ?

3 Answers

Something like below should work. Check and try

<div className={"defaultClass1 defaultClass2 " + (player_color === 1? 'bg-green' :'bg-opponent')}>
<p>Body</p>

No you cannot , You can have the classes separate in css and still call both just using the class="class1 class2" in the html. You just need a space between one or more class names

const myClassNames = `defaultClass1 defaultClass2 bg-${player_color === 1 ? 'green' : 'opponent'}
<div class={myClassNames}>
      <p>Body</p>
</div>

Or you can use this

Related