Home > OS >  loop through 2 array of objects at a time using map in react
loop through 2 array of objects at a time using map in react

Time:07-20

I have a basic react question which i have digged enough but no conclusive result yet. hope someone can enlighten me here.

I have an array of objects as shown below

let response = [
  { "id": 1, "title": "Title 1" },
  { "id": 2, "title": "Title 2" },
  { "id": 3, "title": "Title 3" },
  { "id": 4, "title": "Title 3" }
]

I have a function component which takes in this response and loop through the array of objects and displays the data as shown below

{ response.map((data, index) => {
      return <div>{data.title}</div>
  })
}

This is pretty simple where i display each title one below the other in next line. However, i want to display data in a different way.

I need to show Title 1 and Title 2 in same line beside each other (Title 1 on left side and Title 2 on right side) and Title3 and Title 4 in next line and so on.

How do i achieve that ? because the current map function allows to pass only one title each time

CodePudding user response:

To display the two data in a row, you can use Edit react-17 (forked)

To split up the items with certain width then include flex-basis and assign value in % so that it will be responsive across the screens.

Add css like this,

<div className="item" style={{ "flex-basis": index % 2 ? "80%" : "20%" }}>{data.title}</div>

CodePudding user response:

you can do this with a little trick of CSS. simply add the style={{ width: "calc(100% / 2)"}} to your div style

  {response.map((data, index) => {
    return (
      <span
        style={{
          width: "calc(100% / 2)"
        }}
      >
        {data.title}
      </span>
    );
  })}

Hope it will work for you.You can also check this link https://codesandbox.io/s/react-17-forked-f17gig?file=/src/App.js

CodePudding user response:

I saw in your comment you were asking how to control the grid sizes. Change the sandbox from @Maniraj container css to.

.container {
  display: grid;
  grid-template-columns: [first] 100px [line2] 80px;
}

You can use grid to make it two columns add control the size like above.

  • Related