Overriding JSX attributes with JSX spread attributes

Viewed 522

JSX does not allow an attribute to be specified more than once.

F.ex.

<Component prop1="a" prop1="b" />        /* <- This is not allowed */

I was wondering what happens if an attribute is specified once explicitly but, additionally, another spread attribute that contains the same attribute is passed to the component:

<Component prop1="a" {...obj} />         /* where obj contains an attribute called "prop1" */

Will the order of attributes be important? E.g. will the second attribute override the first one?

1 Answers

The prop that comes 2nd will override the first.

In this case prop1 will be "b".

ex:

const obj = {prop1: 'b' };
return (<Component prop1="a" {...obj} />);

This follows how object spreading works.

MDN Spread Syntax

ex:

const a = { prop1: 'a' };
const b = { prop1: 'b' };
const c = { ...a, ...b };

Object c will have a prop1 of "b" because object b was spread in 2nd.

ex: Code Sandbox

edit: For additional proof and docs from react: Spread attributes in react

Related