user1941537
user1941537

Reputation: 6675

Conditional rendering in React based on state

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?

Upvotes: 1

Views: 808

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281626

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>)
: '';

Upvotes: 2

Umair Farooq
Umair Farooq

Reputation: 1823

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

Upvotes: 2

Related Questions