Keys question - React + Material UI [Solved]


#1

Gents,

Quick question. I use Material UI and React in my project. How do I apply keys properly to my react components?

As an example, below I am doing a map on collection users and returning:

return (
      <span style={styles.wrapper}>
        {users
          .map((x) => (
            <NMSToUsersChip
              user={x}
              conversation={this.props.conversation}
            />
          ))
        }
      </span>
    );

And then say my sub component render looks like:

return (
      <span>
        <Chip
          style={styles.chip}
          backgroundColor={ (this.selected) ? red300 : ''}
          labelColor={ (this.selected) ? white : ''}
          onTouchTap={this.handleTouchTap.bind(this, this.props.user)}
        >
          { (this.selected) ? <Avatar size={32}>T</Avatar> : ''}
          {user.profile.name.first} {user.profile.name.last}
        </Chip>
      </span>
    );

Question: React is going to complain now. Specifically in this case:
warning.js:44 Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method ofNMSToUsers. See https://fb.me/react-warning-keys for more information.

  1. I understand it wants keys. Why - its seems to work fine without keys - I mean i kinda understand why, but can someone explain this to me?
  2. So the keys are so every component does not re-render. Ok. So what is best practise for setting these… should I just go key={math.random()} everywhere and not worry about it? Have i missed the point, i.e. (a)…
  3. Is there a way to handle this automatically? It seems like a pain in the proverbial.

Thanks so much in advance.

Tat


#2

You can usually just use the array index. Luckily, map calls the iterator with the index as the second parameteR:

return (
      <span style={styles.wrapper}>
        {users
          .map((x, index) => (
            <NMSToUsersChip
              key={index}
              user={x}
              conversation={this.props.conversation}
            />
          ))
        }
      </span>
    );

#3

Legend. Thanks so much. Works perfectly.

Tat