Search code examples
listreact-nativekeyaccordionreact-native-paper

How to handle key prop in a list?


Can you help me try to correct this code ?

I would like to make sure I have a list of customer orders. Each order must be able to be unrolled so that we can access the details of the number of items, their detail and the price of the order. I wanted to try to do this with react-native-paper and the list component of this package. However, I get an error on the key of each item. How can I solve it? Thanks for your help.

> Warning: Each child in a list should have a unique "key" prop.

import * as React from 'react';
import { ScrollView } from 'react-native';
import { List } from 'react-native-paper';

const Completed = () => {
  const [expanded, setExpanded] = React.useState(true);

  const handlePress = () => setExpanded(!expanded);

  const list = [
    {
        title: 'Commande 1',
        date:'01/01/2020',
        icon: 'av-timer'
    },
    {
        title: 'Commande 2',
        icon: 'flight-takeoff'
    },
      {
        title: 'Commande 3',
        date:'01/01/2020',
        icon: 'av-timer'
    },
    {
        title: 'Commande 4',
        date:'01/01/2020',
        icon: 'flight-takeoff'
    },
      {
        title: 'Commande 5',
        date:'01/01/2020',
        icon: 'av-timer'
    },
    {
        title: 'Commande 6',
        date:'01/01/2020',
        icon: 'flight-takeoff'
    },
    
    ]

  return (
    <ScrollView>
  {
    list.map((item, i) => (
    <List.Section title={item.date}>
      <List.Accordion
        title={item.title}
        left={props => <List.Icon {...props} icon="folder" />}>
        <List.Item title="Nombre d'articles : ..." />
        <List.Item title="Prix total : ...€" />
      </List.Accordion>      
    </List.Section>
     ))
  }
</ScrollView>
  );
}

export default Completed;

Solution

  • Add key prop like

    list.map((item, i) => (
        <List.Section title={item.date} key={i.toString()}> // Like here
          ....   
        </List.Section>
    ))