react keys code example

Example 1: react create pillbox for each chunk of array

const brandGroups = brandNames.map((e, i) => {
      return i % chunkSize === 0 ? brandNames.slice(i, i + chunkSize) : null;
    }).filter(e => { return e; });

    const renderBrandsItems = () => {
      const ThreePlusBrands = `${brandNames.slice(0, 3).join(", ")} + ${brandNames.length - 3} more`;
      if (brandGroups.length <= 3) {
        return brandGroups.map((item, i) => {
          return (
            <div key={i}>
              <SelectionLabel>
                {item}
                <ClearIcon
                  className="fa fa-times"
                  data-name={item}
                  onClick={handleBrandClick}
                />
              </SelectionLabel>
            </div>
          );
        });
      }
      return (
        <SelectionLabel>
          {ThreePlusBrands}
          <ClearIcon className="fa fa-times" onClick={onClearBrands} />
        </SelectionLabel>
      );
    };

Example 2: react component key prop

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')
);

Example 3: react loop through array

this.items = this.state.cart.map((item, key) =>    <li key={item.id}>{item.name}</li>);