0

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?

1
  • How do you create the array of components to begin with? Wouldn't it be easier to pass all of the necessary props there? Commented Oct 8, 2021 at 14:50

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

When I try that I get the following error: "Component Exception: attempted to assign to readonly property"
jsfiddle.net/7gnLv48u Try React.cloneElement to create a clone of your component and add additional props
Thanks for the jsfiddle, very helpful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.