Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React object spread (ES6) returned from map

Why is this working:

return elements.map((e)=> {return Object.assign({}, e, {selected:true})});

But this doesn't:

return elements.map((e)=> {...e, {selected: true}});

?

New to ES6 / Babel / React, have mercy.

UPDATE: After moving to this (as suggested):

return elements.map(e => ({...e, selected: true }));

Get this error: unexpected token

Though the spread is working elsewhere in the project:

        return [
            ...state,
            element(undefined, action)
        ]
like image 642
Guy Avatar asked Dec 07 '22 21:12

Guy


1 Answers

An implicit return of an object from an arrow function should be wrapped in parens so the interpreter knows it's not a block.

So return elements.map(e => ({...e, selected: true }));

Also fixed the syntax for the selected property, it shouldn't be wrapped in brackets as azium pointed out.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Your unexpected token error is probably due to babel not supporting the proposed object spread. Array spread is es6. Using the plugin as in the answer below will solve this issue. My preferred way to include object spread is babel stage 0, as you also get other cool features like the :: binding operator. Object spread is stage 2, so you could also use that if you don't want to include stages 1 and 0.

https://babeljs.io/docs/plugins/preset-stage-0/

like image 160
Andy_D Avatar answered Dec 11 '22 11:12

Andy_D