3

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" ?

Suhas
  • 55
  • 9
  • maybe you will fund soliton here : https://stackoverflow.com/questions/5482677/how-to-apply-two-css-classes-to-a-single-element/38942058 – نور Aug 17 '20 at 06:13
  • @AbdullahAlNoor .. I did check that question.. that is completely different, it doesn't deal with conditional classes...anyway, the solution by did help me! thank you btw – Suhas Aug 17 '20 at 06:16

3 Answers3

4

Something like below should work. Check and try

<div className={"defaultClass1 defaultClass2 " + (player_color === 1? 'bg-green' :'bg-opponent')}>
<p>Body</p>
K K
  • 17,794
  • 4
  • 30
  • 39
  • Thanks... that indeed solve the issue.. I didnt find this solution in first place when i was browsing... Later i found this : https://scriptverse.academy/tutorials/reactjs-add-class-conditionally.html which might be useful for others! – Suhas Aug 17 '20 at 06:11
0

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

CrazyWolf
  • 9
  • 1
  • Yeah.. i know classes can be added using spaces.. but my larger question is how to achieve what i need.. i.e how to use conditional classes (if else) – Suhas Aug 17 '20 at 06:02
0
const myClassNames = `defaultClass1 defaultClass2 bg-${player_color === 1 ? 'green' : 'opponent'}
<div class={myClassNames}>
      <p>Body</p>
</div>

Or you can use this

Monzoor Tamal
  • 790
  • 5
  • 15