Devesh Kumar
Devesh Kumar

Reputation: 186

How can I pass multiple values in a single prop in react?

Is there any way where I can pass in multiple values in a single prop?

Right now how it works is I have one component and it takes in lots of values like this:

<div>
  <MyComponent
    valueA={100}
    valueB={90}
    valueC={80}
    valueD={70}
    valueE={60}
  />
</div>

Here for example A and B are related and I want to pass them together like

<div>
  <MyComponent
    valueAB={100, 90}
    valueC={80}
    valueD={70}
    valueE={60}
  />
</div>

It probably needs to be in a single object like this: valueAB={{100, 90}} but I have no idea.

How can I do this and extract both of the values on the other side?

Upvotes: 1

Views: 15292

Answers (2)

ikos23
ikos23

Reputation: 5354

You can pass an array or an object:

// e.g
<MyComponent
    valueAB={[100, 90]}
    valueC={{ a: 100, b: 90}} />

And in MyComponent you will get valueAB prop as array, hence you can do something like:

props.valueAB[0] // 100

Or for objet : props.valueC.a is also 100 .

Upvotes: 9

Genie
Genie

Reputation: 90

I think you can do add them as a one object as you did {{100, 90}} or one array {[100,90]}

and you can easily extract them from the array like this:

let myCompValueABFirst = props.valueAB[0];
let myCompValueABSecond = props.valueAB[1];

Upvotes: 1

Related Questions