0

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>
      )
    }
1
  • What is the error you are getting? Commented Mar 6, 2017 at 7:14

3 Answers 3

1

You need a root element. Like <div></div>

render() {
  <div>
    ...
  </div>
}
Sign up to request clarification or add additional context in comments.

Comments

0

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>
  );
}

1 Comment

I don't want to put it to a variable, I prefer straight render because there's lots of field like this.
0

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>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.