How to pass several props in spread operator in react

First a look in JSX. When you do (scenario 1):

<Component myProp={something} />

The something typically is a JavaScript expression.

When you use the spread operator, like (scenario 2):

<Component {...something} />

Then something should be a JavaScript object.

Your case

Considering objA and objB are two JavaScript objects, you can use them like scenario 2 above:

<Component {...objA} {...objB} />

And they should work as expected.

When you do:

let bothObjects = {...objA, ...arrB};
<Component {...bothObjects} />

Again, it works because bothObjects is too an object. Just one object that happens to have been built based on objA and objB.

The other case:

<Component {...{...objA,...objB}} />

May seem weird, but works perfectly. See, from scenario 2 above, JSX expects (in {...something}) that something is an object. And {...objA,...objB} is an object. Well, it’s actually an expression that “returns” a value of object type, but it’s the same. It works fine.

The last case:

<Component {...objA, ...objB} />

Does not work because the expresion objA, ...objB is not a JavaScript object. It actually means nothing, it is a syntax error. See the error message:

VM2296 babel.js:17994 Uncaught SyntaxError: Babel script: Unexpected token, expected }
  30 | 
  31 |       <Bob
> 32 |         {...objA, ...objB}
     |                 ^

As you can see, after the char A of ...objA, JSX just expected to find the }. But it found a , which is an error (Unexpected token).

What to use?

Considering all three forms that work:

let bothObjects = {...objA, ...arrB};
<Component {...bothObjects} />
<Component {...objA} {...objB} />
<Component {...{...objA,...objB}} />

To say which one is better is just a matter of taste. Pick whatever you think is more readable.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)