Home > front end >  Error relating to props and renderItem in react native flatlist
Error relating to props and renderItem in react native flatlist

Time:05-03

im making a simple hello world type project in react native to familiarize myself with everything before I move onto my first project.

The goal of this one was to display an array with a flatlist, but the kicker was I was going to slowly modularize it (ie. array is stored somewhere else, flatlist uses renderitem, renderitem is a seperate component, ect.)

import React, {useState} from 'react';
import {StyleSheet, Text, View, FlatList} from 'react-native';

function App () { 
  const [orders, setOrders] = useState([
    { customer: 'Clair' , age: 45, item: 'Corn', key: 0},
    { customer: 'Alex' , age: 39, item: 'Tomato', key: 1},
    ]);
  

    const renderer = ({order}) => 
    {

      const customerName = order.customer;
      const itemName = order.item;

      return(
        <Text>I am {customerName} and I would like a {itemName} please</Text>
      );
    };
  

return( 
<View style={styles.container}>
  

  <FlatList
    data={orders}
    renderItem={renderer}
    keyExtractor={(order) => order.key}
  
  />
  
  <Text> Hello World!!!! </Text>
</View>

);

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },

  orderContainer:
  {
    borderColor: 'black',
    borderWidth: 5,
    padding: 20,
    alignItems: 'center',
  },

  listText:
  {
    justifyContent: 'center',
    alignItems: 'center',
  }
});

export default App;

the first dummy mistake ive learned is that you shouldnt declare a "component" (in this case the renderer) inside the main return statement for the app

now I just need to wrap my head around the prop handling. The error specifically has to do with the renderItem line. apparently the prop, which from my understanding should be one of the orders from the useState array, doesnt exist

any help is appreciated :)

CodePudding user response:

The object renderer get is as follows.

item: Object
index : 0 
separators: Object

Thus to get the customer details you need to update your function to follow.

const renderer = ({item}) => 
    {
      const customerName = item.customer;
      const itemName = item.item;

      return(
        <Text>I am {customerName} and I would like a {itemName} please</Text>
      );
    };
  • Related