Reputation: 6870
I am new to React, and I read the doc on if/else statements in JSX files but didn't quite understand how to deal with it.
I have a component:
var Favorite = React.createClass({
getInitialState: function() {
return {
category: this.props.category
}
},
handleClick: function() {
console.log(this.that);
var that = this;
$.ajax({
type: 'POST',
url: Routes.favorite_category_path(this.props.category, { format: 'json' }),
success: function(data) {
that.setState({ category: data });
}
});
},
render: function() {
var divClasses = classNames({
"post-upvote": true,
"post-upvote-upvoted": this.state.category.up_voted
});
return (
<div className={divClasses} onClick={this.handleClick}>
<div className="post-upvote-count">
{this.state.category.up_votes}
</div>
<div>
<div className="category-image">
<a>
<img src={this.props.category.category_picture} height="150" width="200"><h2><span>{this.props.category.name}</span></h2></img>
</a>
</div>
</div>
</div>
);
}
});
And I want to render the same html plus a "hidden" class with the "category-image" if this condition is verified:
this.props.category.ancestry != 'null'
However, I couldn't find where to place my if/else statement since It is not allowed to add it in this file (favorite.js.jsx).
How should I do this ?
Upvotes: 3
Views: 3712
Reputation: 109
You can use like;
<div>
{!this.props.category.ancestry &&
<div className='category-image'>
//content
</div>
}
</div>
Upvotes: 2
Reputation: 66
What you could do is the following:
<div className={'category-image' + this.props.category.ancestry ? 'hidden' : ''}>
Also, why not use the classNames module that you already have to achieve this? Otherwise, you can also use the ternary operator as Chris mentioned.
Upvotes: 2
Reputation: 12410
You need to use ternary's in JSX.
var assumption = <div>this is the assumption</div>
var elseCondition = <div>I guess I need to do this instead</div>
{condition ? assumption : elseCondition}
Instead of simply having variables that consist of valid JSX code like I've shown you can have entire components rendered instead (which are effectively the same thing).
So, your if condition is just checking that the value is this.props.category.ancestry not null (truthy) so your ternary just needs to look like this,
{this.props.category.ancestry ? assumption : elseCondition}
Upvotes: 3