Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading