2

enter image description here

I wanted to display badge/text after which condition is met from two conditions. First condition is that if no openSopts available then show SOLD OUT badge/text and if this condition is not met then check if it is online and then show badge/text of ONLINE. But badge/text is not shown on card component, can you please tell me what mistake i am doing ?

2
  • 2
    Please include code as text not images. Also, a <div> JSX element needs to be used, a statement like if(true){<div />} doesn't actually do anything, it's the same as if(true){1}, the value has to be assigned to something or used in some way. Commented Jun 30, 2022 at 14:53
  • You can use helper function or ternary syntax to render as well, as {props.openSpots === 0 ? <div className="card--badge"> SOLD OUT </div> : <div className="card--badge"> online </div> } Commented Jun 30, 2022 at 14:59

3 Answers 3

2

The JSX being returned does not include the JSX in your if/else statement. It needs to be part of the JSX that's returned in order for it to show up.

You could use ternary expressions to do it like this (add this to the JSX after your return statement, put it wherever you'd like the badge rendered):

{ props.openSpots === 0 ? <div className="card--badge">SOLD OUT</div> : null }
{ props.openSpots > 0 && props.location === "Online" ? <div className="card--badge">Online</div> : null }

You could nest them if you wanted a single statement, but that starts to get difficult to read:

{
   props.openSpots === 0 
      ? <div className="card--badge">SOLD OUT</div> 
      : props.location === "Online" 
         ? <div className="card--badge">Online</div> 
         : null
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are not using the JSX in the rendering part, its just a statement.

Either save the JSX in variable like this:

let badge = null

if (openSpots === 0) {
badge = ..
} else if (..) {
badge = ..
}

// Use it in code 

...
<div class="card-badge">{badge}</div>

Or use conditional rendering inline

2 Comments

This will render the div regardless (even when openSpots > 0 and location !== "Online"), which may not be intended.
Maybe removee the <div> would work, couldnt copy the code since it was image, that's why just added it quickly
0

Just assign your code piece to a variable and then render it wherever you want.😊

...
const badge = openSpots === 0 ? <div className="card--badge">SOLD OUT</div> : <div className="card--badge">Online</div>
...
return (
  <div>
   {badge}
  </div>
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.