0

I am fetching JSON data from an API and then need to display it in a react component. I need to use if/else conditions. For ex. The duration returned by the JSON data might turn out to be 0 or it might not be set at all, in that case, I need to avoid displaying it on the screen. So I need an if/else conditioning inside the row class and display Duration data only if it is being provided by the API, how can I achieve that? I read that JSX doesn't support if/else, what's the alternative in that case?

      <div className="row">
        //if condition needs to go here
        <div className="__section--left">Duration</div>
        <div className="__section--right border">
            {item.durationHours} Hours
            {item.durationMinutes} Minutes
        </div>
      </div>
3

1 Answer 1

5

You can use ternary expression condition ? ifTrue : ifFalse

so it will be something like this

<div className="row">
  //if condition needs to go here
  { this.state.something === 'something' ?
  <div className="__section--left">Duration</div>
  <div className="__section--right border">
    {item.durationHours} Hours
    {item.durationMinutes} Minutes
  </div>
  : null }
</div>

In above code, if condition true you return some component and if false you return nothing.

Sign up to request clarification or add additional context in comments.

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.