Browse Source
Moved non-JSX explanation to Displaying Data. Overhauled JSX in Depth. Added JSX Spread Section.main
committed by
Paul O’Shannessy
4 changed files with 166 additions and 94 deletions
@ -0,0 +1,71 @@ |
|||
--- |
|||
id: jsx-spread |
|||
title: JSX Spread Attributes |
|||
permalink: jsx-spread.html |
|||
prev: jsx-in-depth.html |
|||
next: jsx-gotchas.html |
|||
--- |
|||
|
|||
If you know all the properties that you want to place on a component a head of time, it is easy to use JSX: |
|||
|
|||
```javascript |
|||
var component = <Component foo={x} bar={y} />; |
|||
``` |
|||
|
|||
## Mutating Props is Bad, mkay |
|||
|
|||
If you don't know which properties you want to set, you might be tempted to add them onto the object later: |
|||
|
|||
```javascript |
|||
var component = <Component />; |
|||
component.props.foo = x; // bad |
|||
component.props.bar = y; // also bad |
|||
``` |
|||
|
|||
This is an anti-pattern because it means that we can't help you check the right propTypes until way later. This means that your propTypes errors end up with a cryptic stack trace. |
|||
|
|||
The props should be considered immutable at this point. Mutating the props object somewhere else could cause unexpected consequences so ideally it would be a frozen object at this point. |
|||
|
|||
## Spread Attributes |
|||
|
|||
Now you can use a new feature of JSX called spread attributes: |
|||
|
|||
```javascript |
|||
var props = {}; |
|||
props.foo = x; |
|||
props.bar = y; |
|||
var component = <Component {...props} />; |
|||
``` |
|||
|
|||
The properties of the object that you pass in are copied onto the component's props. |
|||
|
|||
You can use this multiple times or combine it with other attributes. The specification order is important. Later attributes override previous ones. |
|||
|
|||
```javascript |
|||
var props = { foo: 'default' }; |
|||
var component = <Component {...props} foo={'override'} />; |
|||
console.log(component.props.foo); // 'override' |
|||
``` |
|||
|
|||
## What's with the weird `...` notation? |
|||
|
|||
The `...` operator (or spread operator) is already supported for [arrays in ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). There is also an ES7 proposal for [Object Rest and Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread). |
|||
|
|||
In fact, you can already use this in our code base as an experimental syntax: |
|||
|
|||
```javascript |
|||
var oldObj = { foo: 'hello', bar: 'world' }; |
|||
var newObj = { ...oldObj, foo: 'hi' }; |
|||
console.log(newObj.foo); // 'hi'; |
|||
console.log(newObj.bar); // 'world'; |
|||
``` |
|||
|
|||
Merging two objects can be expressed as: |
|||
|
|||
```javascript |
|||
var ab = { ...a, ...b }; |
|||
``` |
|||
|
|||
> Note: |
|||
> |
|||
> Activate experimental syntax by using the [JSX command-line tool](http://npmjs.org/package/react-tools) with the `--harmony` flag. |
Loading…
Reference in new issue