Home > Mobile >  Is there a different way to pass a prop to an element in react?
Is there a different way to pass a prop to an element in react?

Time:09-12

I have an array which has components in this structure let array = [{id: uniqueKeyFunction(), element: <Component key={uniqueKeyFunction() />} />}], I would like to pass that id as a prop to the component, maybe like add it in the map function in the render. Currently the map function looks like array.map(arr=>arr.element). Is there a way to add a prop in this structure since I may not be able to add it at the array level?

CodePudding user response:

You can do it this way

const array = [{ id: uniqueKeyFunction(), element: Component }];

return array.map(({ id, element: Element }) => <Element key={id} someProp={id} />)

CodePudding user response:

You can check out https://reactjs.org/docs/react-api.html#cloneelement.

React.cloneElement

It allows you to override props of a existing component - it's not exactly what you wanted, but maybe close enough?

  • Related