1

I'm sending an API request and render its result in to UI.

Now, for the error-handling, I wanted that if there is an error a div which contains an error message gets rendered in to the UI.

To achieve this I wrote the following ternary condition:

const showError = this.state.error
? `<div className="error-container">
    Error:
      <p>{this.state.error}</p>
   </div>`
: '';

And then used this inside my render method: {showError}

But React see the result as a string and renders the following to the UI:

enter image description here

What am I doing wrong?

2 Answers 2

2

In you render method you can do following:

render() {
  return(
   // ... other components
   {this.state.error && (
     <div className="error-container">
       Error:
       <p>{this.state.error}</p>
     </div>
    )}
    // ... 
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! Thanks. I wasn't aware of this method. What is it called?
It is Inline If with Logical && Operator You can check it reactjs.org/docs/…
2

Problem is that you made showError a string by wrapping the content within ``(backticks) and it no longer remains a JSX expression

Use () instead. Also when you don't want to return anything, you should return null instead of an empty string

const showError = this.state.error
? (<div className="error-container">
    Error:
      <p>{this.state.error}</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.