TonyY
TonyY

Reputation: 703

How to add components to list dynamically in React with no redundant render?

Here is an online sample.

var FruitList = React.createClass({
      render : function() {
        return (
          <div className="container">
            <ul className="list-group text-center">
              {
                Object.keys(this.props.fruits).map(function(key) {
                  count = count + 1;
                  return <li className="list-group-item list-group-item-info">{this.props.fruits[key]+count}</li>
                }.bind(this))
              }
            </ul>
           </div>
         );
       }
     });

I want to add "Cherry" to list. before

As is, it redraws all items redundantly. I hope that orange1 and apple2 need to keep their state with no redraw redundantly.

What the design for dynamic list components is better? after

Upvotes: 7

Views: 8203

Answers (1)

Austin Greco
Austin Greco

Reputation: 33544

Extract your list item into it's own pure component, make sure the props only change when the data actually changes, and use the key prop to let react know which item in the list. This way the list will re-render, but the child FruitItem will only re-render when the props change.

import React, {PureComponent} from 'react';

-

class FruitItem extends PureComponent {
  render() {
    console.log('FruitItem render', this.props.name);
    return (
      <li className="list-group-item list-group-item-info">
        {this.props.name}
      </li>
    );
  }
}

-

Object.keys(this.props.fruits).map((key) => {
  return (
    <FruitItem
      key={key}
      name={this.props.fruits[key]}
    />
  );
})

See working codepen, check the console to watch for re-renders

Upvotes: 4

Related Questions