I have to check weather the user is available, if so the background style is set. I can simply do this via PHP with a if statement, although how would this be done with react?
What I have so far:
<a className={classes} onClick={this.toggleDialog} { theUser.get('isAvailable') == 1 && style={{backgroundColor: "rgba(39, 174, 96, .15)"}} } >
{theUser.get('first_name')}
</a>
There's more than one way to use conditional expressions in React:
If/Else
Prevent rendering with null
Element variables
Ternary operator
Short-circuit operator (&& )
Immediately-Invoked Function Expressions (IIFE)
Subcomponents
High Order Components (HOCs)
If you are new to react I highly recommend to read the following: https://blog.logrocket.com/conditional-rendering-in-react-c6b0e5af381e
Using ternary operator for inline styling:
<a style={ theUser.get('isAvailable') == 1 ? { backgroundColor: "rgba(39, 174, 96, .15)" } : {} } />
It's an option to use class names conditionally , because it's much cleaner: (there's already a great library, classnames ):
const classes = classNames({
'available': theUser.get('isAvailable') == 1,
'italics': true, // Will add `italics` className
'bold': false, // Won't add `bold` className
})
<a className={classes} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.