Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
How to use ternary operator with map?

I'm trying to redirect mealContainer to Meals for showing details of that data. By the way, I'm using mealDB for the API. But the problem is when I click meal categories div for showing details, sometimes it becomes null and sometimes it shows the data. I don't know why it's happened. So I'm trying to show a warning when it will be null by using the ternary operator. How can I do that?

import React, { useState } from "react";
import Meals from "../Meals/Meals";
import "./MealCategory.css";

const MealCategory = ({ mealCategory }) => {
  const { strCategory, strCategoryThumb } = mealCategory;
  const [mealsContainer, setMealsContainer] = useState([]);

  const handleOnClick = (e) => {
    e.preventDefault();
    const categoryName = e.target.innerText;
    const categoryUrl = `https://www.themealdb.com/api/json/v1/1/filter.php?c=${categoryName}`;

    fetch(categoryUrl)
      .then((res) => res.json())
      .then((data) => setMealsContainer(data.meals));
    // .then(data => console.log(data))
  };
  return (
    <div>
      <div onClick={handleOnClick} className="col py-3 text-center">
        <div className="card d-flex flex-row align-items-center">
          <div className="img">
            <img src={strCategoryThumb} className="card-img-top" alt="..." />
          </div>
          <div className="card-body">
            <h1 className="card-title fs-2">{strCategory}</h1>
          </div>
        </div>
      </div>
      {mealsContainer.map((meals) => (
        <Meals meals={meals} />
      ))}
    </div>
  );
};

export default MealCategory;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As you are saying sometimes you get null, so even if you use ternary operator inside map, then also you will get error as you can't run map on an array which evaluates to null. Yes, if your concern is how to use ternary operator inside map, then :

{mealsContainer ?
mealsContainer.map(meals => <Meals meals={meals} />) : <p>Error loading data!</p>
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!