Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
GluePear Avatar asked Aug 30 '17 20:08

GluePear


3 Answers

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

like image 181
Michael Horn Avatar answered Sep 19 '22 06:09

Michael Horn


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>
)
like image 31
Cesar William Alvarenga Avatar answered Sep 17 '22 06:09

Cesar William Alvarenga


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.

like image 41
Danil Speransky Avatar answered Sep 21 '22 06:09

Danil Speransky