I'm using array.map
in my render
method of a React component. It works but I want to know how many rows it's rendering. I'm trying by initialising this.numRows = 0
in my constructor, then incrementing it in the map
callback:
<div>
<p>Number of rows = {this.numRows}</p>
{this.state.members.map((member) => {
if (member.display) {
this.numRows++;
return <p>{ member.name }</p>
}
})}
</div>
But this is still showing zero. Full code here: jsfiddle.net/ra13jxak/. How can I show the number of rows returned?
You might consider filtering the members you want to display first, then displaying the length of the resulting array, and mapping over it to render the members:
Fiddle
render() {
const membersToRender = this.state.members.filter(member => member.display)
const numRows = membersToRender.length
return (
<div>
<p>Number of rows = {numRows}</p>
{
membersToRender.map((member, index) => {
return <p key={index}>{ member.name }</p>
})
}
</div>
);
}
Edit: Thanks Edgar Henriquez, I fixed the key properties warning as you suggested
You can use filter to generate a new array and then use it to show the number of rows and iterate through it. Like this:
const members = this.state.members.filter(member => member.display)
return (
<div>
<p>Number of rows = { members.length }</p>
{members.map(member => <p>{ member.name }</p>)}
</div>
)
I think it's a good idea to extract it to the component:
JSFiddle Example
class App extends React.Component {
constructor() {
super()
this.state = {
members: [
..
],
visibleMembers() {
return this.members.filter(m => m.display)
}
}
}
render() {
const members = this.state.visibleMembers()
return (
<div>
<p>Number of rows = {members.length}</p>
{members.map(m => <p key={ m.id }>{ m.name }</p>)}
</div>
)
}
}
I've added key
attribute to suppress a warning, you can read more about it on React Documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With