Home > OS >  Change the class name of components in react dynamically
Change the class name of components in react dynamically

Time:10-18

in this exemple i have an array of objects and i want to change the class name when the city is ny.

class1{color:red} class2{color:blue}

<div>
          {
              people.map((p,i)=>{
               console.log(p.city==='ny') //true false false true false
               return <div key={i} className={p.city==='ny' ? 'class1' : 'class2'}>{p.name}</div>
              })
          }
</div>

When i run it all names are in blue (class2).

The output i want:

jhon doe (red)
jhane doe (red)
jhane doe (blue)
jhon doe (red)
...

The output i have:

jhon doe (blue)
jhane doe (blue)
jhane doe (blue)
jhon doe (blue)
...

data :

poeple [
{city:'ny',name:'jhon doe'},
{city:'la',name:'jhon doe'},
{city:'la',name:'jhane doe'},
{city:'ny',name:'jhane doe'},
{city:'la',name:'jhon doe'}
]

CodePudding user response:

your array should look like:

const people= [{city:'ny' , name:'jhon doe'}, {city:'fl' , name:'jhane doe'}]

does it contain a city with ny like the above?

CodePudding user response:

Remove ‘’ when you are refering to class1 and class2: {p.city==='ny' ? class1 : class2}

What i mean, instead ‘class1’, put class1 as its an object

  • Related