1
votes

ReactJS JSX has a method for easily adding lots of properties to a component:

var props = {};
props.foo = x;
props.bar = y;
var component = <Component {...props} />;

These are called Spread Attributes.

https://facebook.github.io/react/docs/jsx-spread.html#spread-attributes

The ... notation is called a Spread operator that it used in ES6. This is easy to use if you are rendering out everything on the server side using Babel, etc, but if you are wanting to create and render Components in the browser on the client side, how do you use Spread Attributes for browsers that don't support the ES6 ... Spread operator?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Browser_compatibility

2
as you already know, use BabelBryan Chen

2 Answers

5
votes

Despite the similar syntax, the JSX spread operator is not the same as the ES6 spread operator, and using the former does not require the latter. While a JSX transpiler could turn a JSX tag with a JSX spread operator into JavaScript that uses an ES6 spread operator, in practice they just turn it into ES5 code. To see how Babel does it, try it out on the Babel site. In essence, this:

var obj = { className: 'foo' };
var el = <Component id='bar' {...obj}/>;

...becomes this:

var obj = { className: 'foo' };
var el = React.createElement(Component,
           Object.assign({ id: 'bar' }, obj));

(With slight variations depending on the positions of the attributes.)

No ES6 spread operator needed.

In other words, if you're using a transpiler to turn your JSX into JavaScript—and you are, since no browser supports JSX directly—you don't need to worry about the transpiled code having a spread operator, because you weren't using an ES6 spread operator, you were using a JSX spread operator, and that gets transpiled into something browsers understand.

0
votes

The usual workflow of ReactJS would be transforming the JSX via Babel (by a build tool like Browserify/Webpack) before serving it to the client. Hence you get all the ES6 (or ESNext) goodies.

Getting Started | React