Skip to content
Advertisement

Get size of array returned by map in React render

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement