Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda