AdjunctProfessorFalcon
AdjunctProfessorFalcon

Reputation: 1840

How to pass prop to component from array of components in React

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?

Upvotes: 0

Views: 189

Answers (1)

Rajendra Maniyal
Rajendra Maniyal

Reputation: 36

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

Upvotes: 2

Related Questions