How to use conditional rendering inside map in React

I have a react page that is rendering a list of products that are being returned from a GraphQL API. Once the products are returned, I’m storing them in a state and then render them. How do I only render products that meet certain conditions?

Right now, I’m mapping over the products and rendering each one. This is working correctly. But if I try to use conditional statements, I get errors in my IDE. This is the code I currently have. This is currently working:

async function contactAPI() {
  return await axios({
    url: '',
    method: 'post',
    data: {
      query: `

function App() {  
  const [products, setProducts] = useState([]);

  useEffect(() => {
    async function getData() {
      const res = await contactAPI();
  }, []);

  return (
          { =>           
            <ProductCard productName={p.productName} />

I need to check p.productName to see if it meet certain conditions, and if it does, render it. If not, don’t render. I tried using different conditionals inside of map, but keep getting errors.


map will always return an array of the same length so you’ll be returning some empty elements depending on the condition which isn’t optimal.

Instead filter the data first, and then map over the returned array. That way you’re only mapping over the data you need to display.

const { useState } = React;

function App({ data }) {

  const [ products, setProducts ] = useState(data);

  // In this example we take the list of products in
  // state and return a new array of only those products
  // that aren't soap. We then `map` over that array in our
  // component render
  function getFilteredProducts() {
    return products.filter(product => {
      const name = product.productName.toLowerCase();
      return !name.includes('soap');

  // Get an array of filtered products and then `map` over it
  // to produce the product cards
  return (
      {getFilteredProducts().map(product => {
        return (

function ProductCard({ id, name}) {
  return <div>{id}: {name}</div>;

const data=[{id:1,productName:"Blue Soap"},{id:2,productName:"Beans"},{id:3,productName:"Green Soap"},{id:4,productName:"Sponge"},{id:5,productName:"Chicken"}];

  <App data={data} />,
<script src=""></script>
<script src=""></script>
<div id="react"></div>