Reputation: 4918
Is this the correct way to insert HTML within IF ?
render() {
return (
<div>
{
if (!error) {
<p>Sorry - there was an error</p>
}
else {
<p>{this.state.data}</p>
}
}
</div>
)
}
Upvotes: 1
Views: 51
Reputation: 25862
There are multiple ways you can do this, all are "correct" and or valid ways to do what you are trying to do. It really comes down to your code style and what is readable / makes sense for you... I'll add a few different ways to do this so you can see what I mean and decide what works best for you :)
Ternary operator for conditionals in jsx
<div>
{ error ? <p>Sorry - there was an error</p> : <p>{this.state.data}</p> }
</div>
inline if with logical &&
(aka short-circuit evaluation
)
<div>
{ error && <p>Sorry - there was an error</p> }
{ !error && <p>{this.state.data}</p> }
</div>
another way is to use the if's outside of the return.
render() {
const {error} = this.props
const {data} = this.state
if (error) {
return <p>Sorry - there was an error</p>
}
return <p>{data}</p>
}
Upvotes: 2
Reputation: 314
No, inside the render method , you can do something like :
if(condition) {
return(your html)
}
else {
return(another html)
}
Upvotes: 1