Reputation: 7645
I try to do if else statement by checking if the photo property has item, but failed with below code, need help, I don't know what is wrong. The snytax look fine to me.
render() {
return ( < p > other dom < /p>
< div className = "photo_upload" > {
item.photos.length > 0 ?
< img src = {
item.photos[1]
}/ > : < button className = "btn btn-lg btn-primary" > Browse < /button> }< /div >
< p > more dom < /p>
)
}
Upvotes: 0
Views: 388
Reputation: 13952
Every react render
method must return a single dom element. You're returning three - your < p > other dom < /p>
, your < div className = "photo_upload" >
and your <p> more dom < /p>
. Wrap them in a single div. If you look at the error message you're getting, it should tell you exactly this.
Here's your render method, changed to return a single element, and with some formatting improvements:
render() {
return (
<div>
<p> other dom </p>
<div className="photo_upload">
{ item.photos.length > 0 ?
<img src = {item.photos[1]}/> :
<button className="btn btn-lg btn-primary">Browse</button>
}
</div>
<p> more dom < /p>
</div>
)
}
Upvotes: 0
Reputation: 1298
First, take out < p > other dom < /p>
and < p > more dom < /p>
, because you can only return one thing from your render function. Everything you return must be enclosed within one set of tags.
Other than that, there's nothing inherently wrong with your logic. I would recommend putting as little logic in your JSX templates as possible, although that is more of a stylistic choice.
render() {
const item = item.photos.length > 0
? <img src={item.photos[1]} />
: <button className="btn btn-lg btn-primary">Browse</button>
return (
<div className="photo_upload">
{item}
</div>
);
}
Upvotes: 0
Reputation: 15914
You need a root element. Like <div></div>
render() {
<div>
...
</div>
}
Upvotes: 1