Home > Software engineering >  How to pass prop to component from array of components in React
How to pass prop to component from array of components in React

Time:10-09

Let's say you have an array of components:

var my_array = [ <SomeComponent1 textcolor={defaultFontColor} />, <MyComponent2 textcolor={defaultFontColor} />}, <SomeComponent3 textcolor={defaultFontColor} />}, ...]

And you wanted to iterate over the array, but also pass props to the component (in the example, AComponent):

my_array.map(AComponent => {
      return (
        <View>
          {AComponent}
        </View>
      )
})

How would I pass a prop to {AComponent} in this example?

CodePudding user response:

Consider component as a json object

AComponent = {
   props:{
    prop1: "value for the prop1"
  }
}

So, now you can pass the props you wish like

my_array.map(AComponent => {
  AComponent.props["newProp"] = "propValue"
  return (
    <View>
      {AComponent}
    </View>
  )
})

Or, if you wish to use the props passed while pushing the component in the array you can directly use them in the render() method of the component

  • Related