Home > Back-end >  Rendering Arrays in React
Rendering Arrays in React

Time:11-17

i am trying to render the sub array as an individual item, but it keeps rendering all the sub array items inside one list `

 const items = [
    { id: 1, header: "Global", lst: "All Fruits" },
    {
      id: 2,
      header: "By Taste",
      lst: ["sweet", "sour", "bitter"],
    },
    {
      id: 3,
      header: "By Region",
      lst: [
        "Tropical",
        "dry",
        "Continental",
        "Temperate",
        "Polar",
      ],
    },
  ];

`

`

<ul className="dd-list">
          {items.map((item) => (
            <div key={item.id}>
              <i>{item.header}</i>

              <li className="dd-list-item">
                <button
                  type="button"
                  onClick={(e) => {
                    setSelected(item.lst);
                    setOpen(false);
                  }}
                >
                  {item.lst}
                </button>
              </li>
            </div>
          ))}
        </ul>

` this is the result

thanks in advance

expected result

By Taste -sweet -sour -bitter By Region -Tropical -dry -Continental -Temperate -Polar

CodePudding user response:

You should add inner list

  <ul className="dd-list">
    {items.map((item) => (
      <li key={item.id}>
        <i>{item.header}</i>
        <ul>
          {item.lst.map((innerItem) => (
            <li key={innerItem} className="dd-list-item">
              <button
                type="button"
                onClick={(e) => {
                  setSelected(innerItem);
                  setOpen(false);
                }}
              >
                {innerItem}
              </button>
            </li>
          ))}
        </ul>
      </li>
    ))}
  </ul>

CodePudding user response:

You need to iterate on the lst items inside your items. I've noticed that the first object inside your items is not an array

Solution


 const items = [
    { id: 1, header: "Global", lst: ["All Fruits"] },
    {
      id: 2,
      header: "By Taste",
      lst: ["sweet", "sour", "bitter"],
    },
    {
      id: 3,
      header: "By Region",
      lst: [
        "Tropical",
        "dry",
        "Continental",
        "Temperate",
        "Polar",
      ],
    },
  ];

return <ul className="dd-list">
    {items.map((item) => (
      <li key={item.id}>
        <i>{item.header}</i>
        <ul>
          {item.lst.map((innerLstItems,index) => (
            <li className="dd-list-item" key={index}>
              <button
                type="button"
                onClick={(e) => {
                  setSelected(innerLstItems);
                  setOpen(false);
                }}
              >
                {innerItem}
              </button>
            </li>
          ))}
        </ul>
      </li>
    ))}
  </ul>
  • Related