1

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>
  )
}
1
  • What do you mean by "correct?" Commented Jul 14, 2018 at 18:04

2 Answers 2

2

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>
}
Sign up to request clarification or add additional context in comments.

2 Comments

The "logical &&" is called a short-circuit evaluation.
@Chris Yep thanks for clarifying. I titled it that to follow what the react docs say so its easier to see the example and what its referencing. I'll update to include the correct technical term though! thanks!
1

No, inside the render method , you can do something like :

if(condition) {
return(your html)
} 
else {
return(another html)
}

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.