Lists and Keys
Rendering Multiple Components

//index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id = "root"></div>
	<script src="https://fb.me/react-0.14.3.js"></script>
	<script src="https://fb.me/react-dom-0.14.3.js"></script>
	<script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
	<script src="script.js" type = "text/babel"></script>
</body>
</html>
		
//script.js
function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key = {number.toString()}>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
	<NumberList numbers = {numbers}/>,
  document.getElementById('root')
);
		
Keys
  • Keys help React identify which items have changed, are added, or are removed
  • Keys should be given to the elements inside the array to give the elements a stable identity
  • keep the key on the <ListItem /> elements in the array rather than on the <li> element in the ListItem itself
  • Keys used within arrays should be unique among their siblings, however they don’t need to be globally unique
  • Keys serve as a hint to React but they don’t get passed to your components
  • function ListItem(props) {
      // Correct! There is no need to specify the key here:
      return <li>{props.value}</li>;
    }
    
    function NumberList(props) {
      const numbers = props.numbers;
      const listItems = numbers.map((number) =>
        // Correct! Key should be specified inside the array.
        <ListItem key={number.toString()}
                  value={number} />
    
      );
      return (
        <ul>
          {listItems}
        </ul>
      );
    }
    
    const numbers = [1, 2, 3, 4, 5];
    ReactDOM.render(
      <NumberList numbers={numbers} />,
      document.getElementById('root')
    );
    		
    Reference
  • reactjs.org