0

How can I implement this?

I want to map through the plans array and for each item render a list. while This is working, in case if we have null or undefined on a title, we still have 4 Li tag renders which the second one doesn't have any content. but how can I implement this if the title is null/undefined the object get ignored and move to next object and render the rest of the array.

Hope my explanation is clear.

import React from "react";


const App = (props) => {

  const plans = [
    {
      title: "Starter",
      plan: "plan_0",
    },
    { title: undefined,
      plan: "plan_1A",
    },
    {
      title: "Classic",
      plan: "plan_2A",
    },
    {
      title: "Premium",
      plan: "plan_3A",
    },
  ];


  return (
    <div>

      <h1>Notes</h1>
   
      <ul>
        {plans.map((plan, i) =>
            <li className="something" key={i}>
              <span className="somethingels">{plan.title}</span>
            </li>
        )}

      </ul>

    </div>
  );
};

export default App;

at the moment its render like this :

  • Starter
  • Classic
  • Premium
  • <li>Starter</li>
    <li></li>
    <li>Classic</li>
    <li>Premium</li>
    
    Kim-Jun-Un
    • 83
    • 2
    • 11

    2 Answers2

    0

    Just adding a conditionnal statement should do the trick :

        {plans.map((plan, i) =>
            { plan.title &&
                <li className="something" key={i}>
                    <span className="somethingels">{plan.title}</span>
                </li>
            }
        )}
    
    0

    check to see that plan has a property of title before rendering a list item :)

      <ul>
        {plans.map(
          (plan, i) =>
            plan.title && (
              <li className="something" key={i}>
                <span className="somethingels">{plan.title}</span>
              </li>
            )
        )}
      </ul>
    
    • if I understand it correctly, it is like: if plan.title exists then go ahead and render it. right? – Kim-Jun-Un Oct 21 '21 at 18:57
    • exactly if plan.title returns truthy, then it continues to what comes after the '&&' operator. Otherwise, it will skip that chunk of code – johnnyrwest Oct 21 '21 at 21:09