I create a new react component called that displays some user info. I have every user data in an array of objects. I want to create a layout that shows every 3 users in a row container (columns for Bulma css framework) with a column element for each user.
I check others questions like this create new row after every 3 column in loop and all use non-closing tags in HTML for creating the layout but in React.js all the tags must have a closing tag.
users: [
{id:1, name: Tomas}
{id:2, name: Tomas}
{id:3, name: Tomas}
{id:4, name: Tomas}
{id:5, name: Tomas}
{id:6, name: Tomas}
]
return (
////
const users = users.map(user,index) => {
if (index % 3 === 0) {
/// some code to create the layout
}
return <div className="column><User name={client.name}/></div>
}
///
)
I want to render something like this
<div className="columns">
<div className="column">
<User id={users.id} name={users.name}/> // id 1
<div>
<div className="column">
<User id={users.id} name={users.name}/> // id 2
<div>
<div className="column">
<User id={users.id} name={users.name}/> // id 3
<div>
</div>
<div className="columns">
<div className="column">
<User id={users.id} name={users.name}/> // id 4
<div>
<div className="column">
<User id={users.id} name={users.name}/> // id 5
<div>
<div className="column">
<User id={users.id} name={users.name}/> // id 6
<div>
</div>
How can I make this layout?
In React you can't generate code like you would do with server rendering like PHP or Ruby.
First, you have to split your array into sub arrays, and you can define a method for it:
const splitEvery = (array, length) =>
array.reduce(
(result, item, index) => {
if ( index % length === 0 ) result.push([])
result[Math.floor(index / length)].push(item)
return result
},
[]
)
Then, in your render method, you can cycle the splitted array:
return (
<div>
{
splitEvery(users, 3).map(usersChunk => (
<div className="columns">
{ usersChunk.map( user => (
<div className="column">
<User key={user.id} id={user.id} name={user.name} />
<div>
))
}
</div>
)
}
</div>
)