user1589188
user1589188

Reputation: 5736

Spreading multiple props with the same property in JSX

Given two props objects:

const p1 = {
  id: "p1"
  //...
}

const p2 = {
  id: "p2"
  //...
}

If spreading them both on the same component, like:

<MyComponent {...p1} {...p2}/>

How React is to determine what property value id to use?

May also consider other cases like

<MyComponent {...p1} id={"p3"} {...p2}/>
<MyComponent id={"p3"} {...p1} {...p2}/>

Basically, whats the rule behind to tell which property value is the value it uses?

Upvotes: 1

Views: 477

Answers (1)

tar
tar

Reputation: 1568

In the order they appear, left to right. It'll walk through the first spread, assigning props, then through the second, overwriting any duplicates.

Demonstration:

const Printout = (props: { x: number; y: number; z: number }) => {
  useEffect(() => console.log(props), [props]);
  return null;
};

const Demo = () => {
  const a = { x: 1, y: 2, z: 3 };
  const b = { y: 5, x: 6 };
  return <Printout {...a} z={4} {...b} />;
};

Console output:

{"x": 6, "y": 5, "z": 4}

The order that keys are obtained from an object is a different question. See Does JavaScript guarantee object property order? for example.

Upvotes: 6

Related Questions