Reputation: 765
I want to render html elements if the data is loaded.
render() {
return (
<div>
...
{ this.state.isLoaded ?
(
<ReviewShortIntro review={this.state.mainReview} />
<div className="clear" />
<div className="section-title"></div>
<ReviewList reviews={this.state.reviews} />
)
}
</div>
);
But this shows an error as below.
SyntaxError: this is a reserved word (60:35)
The 60th line is
<ReviewShortIntro review={{this.state.mainReview}} />
Without conditional flag (in the code, this.state.isLoaded), i have to check all properties of review is undefined or not.
I am not familiar with react.
What is my best way for resolve problem?
Upvotes: 0
Views: 363
Reputation: 6691
According to the documentation use the &&
operator and you should wrap it in a single element. I recommend to use Fragment
which do not generate unnecessary dom elements:
import React, { Fragment } from 'react';
render() {
return (
<div>
...
{this.state.isLoaded && (
<Fragment>
<ReviewShortIntro review={this.state.mainReview} />
<div className="clear" />
<div className="section-title"></div>
<ReviewList reviews={this.state.reviews} />
</Fragment>
)
}
</div>
);
Upvotes: 1
Reputation: 85545
Replace this:
<ReviewShortIntro review={{this.state.mainReview}} />
With this:
<ReviewShortIntro review={this.state.mainReview} />
However, I couldn't see using {{}}
inside the post, but just seeing in your error message. Thus, you need to confirm you're using this.state.mainReview
inside single curly brace.
The double curly brace means you're defining an object. And object has key:value
pair. So, using {{this.state.mainReview}}
will cause you such error as there's no such key:value
pair.
Though, it might be a typo rather in your code. Just answered to inform that calling a function or whatever the state should be wrapped inside a single curly brace.
Ah and yes, your ternary operator is incomplete. Use && operator or complete the ternary operator:
{ this.state.isLoaded ?
(
<ReviewShortIntro review={this.state.mainReview} />
<div className="clear" />
<div className="section-title"></div>
<ReviewList reviews={this.state.reviews} />
) : ''
}
Upvotes: 0
Reputation: 64526
Your ternary operator is incomplete, you only have the left side. You're missing the : null
part.
You need to wrap multiple elements in a parent element so that you only return a single element. For example, wrapped in a <div>
:
render() {
return (
<div>
...
{ this.state.isLoaded ?
(
<div><ReviewShortIntro review={this.state.mainReview} />
<div className="clear" />
<div className="section-title"></div>
<ReviewList reviews={this.state.reviews} /></div>
) : null
}
</div>
);
Upvotes: 1