Home > Net >  How to dynamically set keys for list items in React
How to dynamically set keys for list items in React

Time:08-01

I'm trying to dynamically set key for list items but to no success.

My attempt so far doesn't work and fails with :

ERROR Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

My approach :

export default function MyDynamicView() {
  return {
    id: 1,
    view: () => {
      return (
        <View></View>
      );
    },
  };
}


<View>
  {dynamicViewsArr.map(MyDynamicView => (
    <MyDynamicView.view key={MyDynamicView.id} />
  ))}
</View>

How can I do this right?

Thank you in advance.

CodePudding user response:

You can do like below

    const MyDynamicView=({data})=> {
  return {
    <View></View>
  };
}

<View>
  {dynamicViewsArr.map(MyDynamicView => (
    <MyDynamicView key={MyDynamicView.id} data={<ITEM OBJ>} />
  ))}
</View>
  • Related