Home > Software design >  conditional rendering to display in React
conditional rendering to display in React

Time:06-30

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 ?

CodePudding user response:

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
}

CodePudding user response:

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 >{badge}</div>

Or use conditional rendering inline

CodePudding user response:

You are not using the condition on your rendering, the condition needs to be inside your JSX rendering

here is an example:

import React from 'react';

export default function Card(props) {
  return (
    <div className="card">
      {props.openSpots === 0 ? (
        <div className="card--badge">SOLD OUT</div>
      ) : (
        <div className="card--badge">Online</div>
      )}
      <img src={`…./images/${props.img}`} className="card--image" />
      <div className="card--stats">
        <img src=".. /images/star.png" className="card--star" />
        <span>{props.rating}</span>
        <span className="gray">{props.reviewCount}</span>
        <span className="gray">{props.location}</span>
      </div>
      <p className="card--title">{props.title}</p>

      <p className="card--price">
        <span className="bold">From ${props.price}</span>
        person
      </p>
    </div>
  );
}
  • Related