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
  • 62,658
  • 20
  • 139
  • 163
Alex Horvath
  • 33
  • 1
  • 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

4

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,589
  • 2
  • 21
  • 34
2

You can do something like this:

<div style={{ visibility: this.state.post.type === 'team_member'? 'green': ''}}></div>
Badal Saibo
  • 2,499
  • 11
  • 23
Akhter Al Amin
  • 852
  • 1
  • 11
  • 25
1

You can do something like this:

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