admin管理员组

文章数量:1296454

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!

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!

Share Improve this question edited Nov 22, 2018 at 16:55 nanobar 66.5k25 gold badges152 silver badges175 bronze badges asked Nov 22, 2018 at 16:38 Alex HorvathAlex Horvath 331 gold badge1 silver badge5 bronze badges 1
  • Possible duplicate of Correct way to handle conditional styling in React – nanobar Commented Nov 22, 2018 at 16:57
Add a ment  | 

3 Answers 3

Reset to default 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!

You can do something like this:

<div style={{ visibility: this.state.post.type === 'team_member'? 'green': ''}}></div>

You can do something like this:

<div style={ post.type === "team_member" ? {backgroundColor : "green" }: '' }}></div>

本文标签: javascriptconditional styling in ReactStack Overflow