Emperor Krauser Emperor Krauser - 7 days ago 6
React JSX Question

How can you display an specific number of rendering after mapping a json object?

This is my json object.

"properties":{

"summary":[
{
"id":0,
"name": "John Doe",
"address": "Privet Drive",
"sex":"M"
},
{

"id":1,
"name": "John Smith",
"address": "Elm Street",
"sex":"M"
},
{

"id":2,
"name": "Jane Doe",
"address": "Privet Drive B",
"sex":"F"
},
{

"id":3,
"name": "Peter Parker",
"address": "Privet Drive C",
"sex":"M"
},
{

"id":4,
"name": "Harry Potter",
"address": "Privet Drive D",
"sex":"M"
}
]

}


This is the on my react file

class Thumbnail extends React.Component{
render(){
const datax = this.props.info;

return (
<div>
{
datax.map(function(obj){
{
let summary = obj.properties.summary;
let summaryLength = summary.length;

return (
summary.map(function(item){

return <div className={"col-md-3 col-sm-6"} key={item.id}>
<p>
<a href={'http://localhost:8080/'} className="listing-link">
<PersonName name={item.name} />
</a>
</p>
<PersonAddress address={item.address} />
<PersonSex address={item.sex} />
</div>;

})
)
}
})
}
</div>
)
}
}


The ReactDom.render is on a different file which I can access by this:

ReactDOM.render(<Thumbnail info={data} />, document.getElementById('featured-list'));


I want to display only 4 sets of properties from the props object. This code displays 5 of them based on the props which has 5 sets.

I tried doing a iteration inside the map function but it fails.

How can I achieve this?

Answer

You can use slice to display only first four sets. You can try like this :

summary.slice(0,4).map(function(item){ .... })

That will return only first four sets. Here is a fiddle

Another solution

With the iteration inside the map function, you can do it like this :

{summary.map((s, i) => i <= 3 ? <div key={i}>{s.name}</div> : "")}

That will also return only first four sets. Here is a fiddle.

Hope this helps.