3

In React can I do something like this:

style={ $post.type === "team_member" ? backgroundColor : "green"}

How can I style according to a condition in React?

Thank you in advance!

Dominic
  • 56,023
  • 17
  • 130
  • 152
Alex Horvath
  • 33
  • 1
  • 5
  • Possible duplicate of [Correct way to handle conditional styling in React](https://stackoverflow.com/questions/35762351/correct-way-to-handle-conditional-styling-in-react) – Dominic Nov 22 '18 at 16:57

3 Answers3

3

You can, and it's close to what you already have;

style={{backgroundColor: $post.type === "team_member" ? 'green': 'not_a_team_member'}}

The style attribute expects an object, hence the double {}, you're only assigning the value of backgroundColor conditionally, so the conditional is the value of the key backgroundColor in the object.

Hope this helps!

Mike Donkers
  • 3,461
  • 1
  • 20
  • 33
2

You can do something like this:

<div style={{ visibility: this.state.post.type === 'team_member'? 'green': ''}}></div>
Badal Saibo
  • 1,212
  • 8
  • 15
Akhter Al Amin
  • 762
  • 1
  • 9
  • 25
1

You can do something like this:

<div style={ post.type === "team_member" ? {backgroundColor : "green" }: '' }}></div>
Chris
  • 720
  • 1
  • 8
  • 17