Home > Blockchain >  How to iterate through and render two lists in react side by side?
How to iterate through and render two lists in react side by side?

Time:10-28

I have a use case to render two lists in parallel side by side in react.

Inputs :

List 1 : [A, B, C] List 2 : [X, Y, Z]

Expected output (A, B, C are left aligned and X, Y, Z are right aligned) :

A             X
B             Y
C             Z

Before I have only seen cases where traversal of single list is done, could someone please help with example where traversal of both lists can be done?

Thanks

CodePudding user response:

There are a few approaches that might be suitable, I would probably go for flex-box approach. You could render each list inside a flex-box with flex-direction column. Then you could put both lists inside another flex-box which has flex-direction row:

export default function App() {
  const list1 = ["A", "B", "C"];
  const list2 = ["X", "Y", "Z"];

  return (
    <div style={{ display: "flex", flexDirection: "row" }}>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {list1.map((item) => (
          <div>{item}</div>
        ))}
      </div>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {list2.map((item) => (
          <div>{item}</div>
        ))}
      </div>
    </div>
  );
}

You could simplify that a little as well:

function List(props) {
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {props.list.map((item) => (
        <div>{item}</div>
      ))}
    </div>
  );
}

export default function App() {
  const list1 = ["A", "B", "C"];
  const list2 = ["X", "Y", "Z"];

  return (
    <div style={{ display: "flex", flexDirection: "row" }}>
      <List list={list1} />
      <List list={list2} />
    </div>
  );
}
  • Related