Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda