Search code examples
arraysreactjsreact-props

How to add a prop to components inside an array?


I have an array with a bunch of React components without a key prop.

I'd like to loop over them and add it.

How can I do it?

Example:

const elements = [<Component someProp={someValue}/>, <Component someProp={someValue}/>];

elements.forEach((item,index) => {
  // HOW CAN I ADD key TO THE COMPONENTS HERE ?
});

PS: Yes, I can do it when I'm creating the array, but I chose not to, in order to improve readability.

Is it possible?


Solution

  • const elements = [<Component someProp={someValue}/>, <Component someProp={someValue}/>];
    
    elements.map((item,index) => {
      return React.cloneElement(item, {
         someNewProp
      }
    });
    

    this Key is React.cloneElement