Home > Back-end >  How to cleanly create duplicate components with different parameters in react native/typescript?
How to cleanly create duplicate components with different parameters in react native/typescript?

Time:06-06

I have a bunch of components that looks like this:

<View>
<Component
   containerStyle={{ color: 'blue' }}
   id={"test1"}
   onPress={onPress1}/>
 <Component
   containerStyle={{ color: 'blue' }}
   id={"test2"}
   onPress={onPress2}/>
 <Component
   containerStyle={{ color: 'blue' }}
   id={"test3"}
   onPress={onPress3}/>
  ...
 </View>

How can I create this cleanly in code without manually making a long list of these components?

CodePudding user response:

Please check: (https://reactjs.org/docs/lists-and-keys.html). You can use map method of Arrays:

...
const elementsProps = [
  {
    containerStyle: {color: 'blue'},
    id: 'test1',
    onPress: onPress1
  },
  {
    containerStyle: {color: 'blue'},
    id: 'test2',
    onPress: onPress2
  },
  {
    containerStyle: {color: 'blue'},
    id: 'test3',
    onPress: onPress3
  },
];
return (
  <View>
    {elementsProps.map((element) => (<Component key={element.id} {...element} />)}
  </View>
);

You have to pass additional property: key, which is required in order to optimise list. If elements change their order, key property helps to move elements in DOM rather than rerendering them from scratch. That's why it's not recommended to use index as a key, as it will change for the element when order is changed.

  • Related