rysv
rysv

Reputation: 3400

Dynamically add a prop to a ReactJS object

I have this object created as follows

let comp = <MyComponent
  msg="hello"
>

Now I want to add another property foo="bar" to object comp. I could always have something like

let comp = <MyComponent
  msg="hello"
  foo={this.state.barOrNoBar}
>

But I am getting an array of these objects from another piece of code and cannot add foo there. I just want to add this property only as needed. What is the right way to do this (other than doing a DOM findNode and using setAttribute)?

Upvotes: 0

Views: 34

Answers (1)

peter bray
peter bray

Reputation: 1345

You can create a functional component like this:

const MyComp = ({barOrNone = null}) =>
  <MyComponent msg="hello" foo={barOrNone} />;

And then, to use it:

<MyComp barOrNone={this.state.barOrNone} />

Upvotes: 1

Related Questions