How to show results of a map in two or more columns using react
Will there always be 2 columns, regardless of how many items you have? If there are 5 items, should it display as col A -> 1,2,3. col B -> 4,5? Use CSS to put the two columns side by side.
var halfwayPoint = Math.ceiling(this.props.result.length / 2)
var columnA = this.props.result.splice(0, halfwayPoint)
var columnB = this.props.result.splice(halfwayPoint)
render () {
return (
<div className='columnA'>
{columnA.map((item, i) => {
return (
<div>{item.value}</div>
)
})
}
</div>
<div className='columnB'>
{columnB.map((item, i) => {
return (
<div>{item.value}</div>
)
})
}
</div>
)
}
If you always want exactly two columns, then one option is to call map
twice. Once for each half of the array:
const secondColumnStart = Math.floor(this.props.result.length / 2);
return (
<div className="row">
<div className="col-md-6">
{this.props.result.slice(0,secondColumnStart).map(item => item.value)}
</div>
<div className="col-md-6">
{this.props.result.slice(secondColumnStart).map(item => item.value)}
</div>
</div>
);
Simply map items as you usually do from one array. With that, use the CSS property "columns" to display them as described in the question above.
.container {
columns: 2 auto;
}
Assuming two column's, having col-md-6
class for row splitting.
create stateless component myRow
const myRow = ({index})=>{(<div className="col-md-6">{index}</div>)}
create array for each cols
const col1 = [],col2 = [];
this.props.result.forEach((item, i) => {
if(i%===0){
col1.push(myRow);
}else{
col2.push(myRow);
}
}
return the React element in render.
return <div className="row">
{col1}{col2}
</div>;