Kimako
Kimako

Reputation: 625

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;

Upvotes: 0

Views: 359

Answers (2)

asaeed
asaeed

Reputation: 21

Make sure to provide a key to the first item in any loop.

In your case add the key to List.Section

<List.Section key={item.title} title={item.date}>
  ........
</List.Section>

Key can be any unique string in your data

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Add key prop like

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

Upvotes: 1

Related Questions