Condition in react js

Viewed 35

I try to use a condition in React, if available above 1 then show spaces and if it's equal 1 then show space. I write code this way, but it doesn't work. Please help me.

import React from "react";

const AppointmentService = ({ service }) => {
  const { name, slots } = service;
  return (
    <div>
      <div className="card lg:max-w-lg bg-base-100 shadow-xl">
        <div className="card-body">
          <h2 className="card-title">{name}</h2>
          <p>
            {slots.length}
            <>{slots.length == 1 ? "space available" : "spaces available"}</>
          </p>
          <div className="card-actions justify-end">
            <button className="btn btn-primary">Buy Now</button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AppointmentService;
2 Answers

put the section you're trying to show on the webpage on a span, div or p tag like below and I've also slighly modified your condition.

<span>
   { slots?.length > 1 ? "spaces available" : (slots?.length === 1 ? "space available" : "No space available")}
</span>

It's been a long time since last time I worked with React, anyway TRY THIS:

<p>{slots.length}
 <>
       { slots.length == 1 ? <>
           "space available" </>
       :
        <>
           "spaces available" </>
        }
 </>
</p>
Related