Search code examples
javascriptreactjses6-map

How to loop over map and generate JSX in React?


This is my map:

const map1 = new Map();

map1.set(0, 'foo');
map1.set(1, 'bar');

I want to generate a UI as

0: foo 1: bar How can I generate this UI?

Thanks for the response.

But basically i have structure

const data = {
  title: "hello lorem ipsum",
  replies: [
    {
      id: "1",
      parentId: null,
      body: "hello here i am",
    },
    {
      id: "2",
      parentId: "1",
      body: "test it out",
    },
    {
      id: "3",
      parentId: "2",
      body: "hello there!",
    },
    {
      id: "4",
      parentId: "3",
      body: "i dont continue testing",
    },
    {
      id: "5",
      parentId: "4",
      body: "this cannot be tested",
    },
    {
      id: "6",
      parentId: "4",
      body: "this is ridiculous",
    },
  ],
};

using this structure i am trying to generate a tree kind of ui which displays as this hello here i am test it out hello there! "i dont continue testing" this cannot be tested. this is ridiculous"

as parent child relationship

i tried to make a datastructure using hashmap as

function buildTreeMap() {
  const treeMap = new Map();
  for (const reply of data.replies) {
    const { id, parentId } = reply;
    let children = [];
    if (!parentId) {
      treeMap.set(id, []);
    } else {
      if (!treeMap.has(parentId)) {
        treeMap.set(parentId, [reply]);
      } else {
        children = treeMap.get(parentId);
        children.push(reply);
        treeMap.set(parentId, children);
      }
    }
  }
  return treeMap;
}

and my intention is to loop through this and generate the ui as mentioned above I know this is similar to preorder


Solution

  • You can use Array.from to convert the Map into an array and then map over it:

    const map1 = new Map();
    map1.set(0, "foo");
    map1.set(1, "bar");
    
    function App() {
      return (
        <section>
          {Array.from(map1).map(([key, value]) => {
            return `${key}:${value}`;
          })}
        </section>
      );
    }
    

    Or, if you want each entry in a new line, replace the return statement like this:

    function App() {
      return (
        <section>
          {Array.from(map1).map(([key, value]) => {
             return <p>{key}:{value}</p>;
          })}
        </section>
      );
    }