0

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?

user1589188
  • 4,159
  • 12
  • 49
  • 99
  • 2
    In increasing level of preference it goes from left to right (or from top to bottom if you split each onto a new line), with subsequent ones overriding all previous ones with the same key – Jayce444 May 18 '21 at 00:38

1 Answers1

5

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.

tar
  • 1,511
  • 1
  • 21
  • 30