Browse Source

Updated Docs for new JSX Changes

Moved non-JSX explanation to Displaying Data.
Overhauled JSX in Depth.
Added JSX Spread Section.
main
Sebastian Markbage 10 years ago
committed by Paul O’Shannessy
parent
commit
836909901e
  1. 44
      docs/02-displaying-data.md
  2. 143
      docs/02.1-jsx-in-depth.md
  3. 71
      docs/02.2-jsx-spread.md
  4. 2
      docs/02.3-jsx-gotchas.md

44
docs/02-displaying-data.md

@ -77,12 +77,50 @@ React components are very simple. You can think of them as simple function that
We strongly believe that components are the right way to separate concerns rather than "templates" and "display logic." We think that markup and the code that generates it are intimately tied together. Additionally, display logic is often very complex and using template languages to express it becomes cumbersome.
We've found that the best solution for this problem is to generate markup directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs. In order to make this easier, we've added a very simple, **optional** HTML-like syntax for the function calls that generate markup called JSX.
We've found that the best solution for this problem is to generate HTML and component trees directly from the JavaScript code such that you can use all of the expressive power of a real programming language to build UIs.
**JSX lets you write JavaScript function calls with HTML syntax.** To generate a link in React using pure JavaScript you'd write: `React.createElement('a', {href: 'http://facebook.github.io/react/'}, 'Hello React!')`. With JSX this becomes `<a href="http://facebook.github.io/react/">Hello React!</a>`. We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
In order to make this easier, we've added a very simple, **optional** HTML-like syntax to create these React tree nodes.
JSX is very small; the "hello, world" example above uses every feature of JSX. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
**JSX lets you create JavaScript objects using HTML syntax.** To generate a link in React using pure JavaScript you'd write:
`React.createElement('a', {href: 'http://facebook.github.io/react/'}, 'Hello!')`
With JSX this becomes:
`<a href="http://facebook.github.io/react/">Hello!</a>`
We've found this has made building React apps easier and designers tend to prefer the syntax, but everyone has their own workflow, so **JSX is not required to use React.**
JSX is very small. To learn more about it, see [JSX in depth](/react/docs/jsx-in-depth.html). Or see the transform in action in [our live JSX compiler](/react/jsx-compiler.html).
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
The easiest way to get started with JSX is to use the in-browser `JSXTransformer`. We strongly recommend that you don't use this in production. You can precompile your code using our command-line [react-tools](http://npmjs.org/package/react-tools) package.
## React without JSX
JSX is completely optional. You don't have to use JSX with React. You can create these trees through `React.createElement`. The first argument is the tag, pass a properties object as the second argument and children to the third argument.
```javascript
var child = React.createElement('li', null, 'Text Content');
var root = React.createElement('ul', { className: 'my-list' }, child);
React.render(root, document.body);
```
As a convenience you can create short-hand factory function to create elements from custom components.
```javascript
var Factory = React.createFactory(ComponentClass);
...
var root = Factory({ custom: 'prop' });
React.render(root, document.body);
```
React already have built-in factories for common HTML tags:
```javascript
var root = React.DOM.ul({ className: 'my-list' },
React.DOM.li(null, 'Text Content')
);
```

143
docs/02.1-jsx-in-depth.md

@ -3,32 +3,51 @@ id: jsx-in-depth
title: JSX in Depth
permalink: jsx-in-depth.html
prev: displaying-data.html
next: jsx-gotchas.html
next: jsx-spread.html
---
JSX is a JavaScript XML syntax transform recommended for use
with React.
[JSX](http://facebook.github.io/jsx/) is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React.
## Why JSX?
React works out of the box without JSX. Simply construct your markup using the
functions on `React.DOM`. For example, here's how to construct a simple link:
You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.
It's more familiar for casual developers such as designers.
XML has the benefit of balanced open and closing tags. This helps make large trees easier to read than function calls or object literals.
It doesn't alter the semantics of JavaScript.
## HTML Tags vs. React Components
React can either render HTML tags (strings) or React components (classes).
To render a HTML tag, just use lower-case tag names in JSX:
```javascript
var link = React.DOM.a({href: 'http://facebook.github.io/react'}, 'React');
var myDivElement = <div className="foo" />;
React.render(myDivElement, document.body);
```
We recommend using JSX for many reasons:
To render a React Component, just a local variable that starts with an upper-case letter:
* It's easier to visualize the structure of the DOM.
* Designers are more comfortable making changes.
* It's familiar for those who have used MXML or XAML.
```javascript
var MyComponent = React.createClass({/*...*/});
var myElement = <MyComponent someProperty={true} />;
React.render(myElement, document.body);
```
React's JSX uses the upper vs. lower case convention to distinguish between local component classes and HTML tags.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect DOM property
> names like `className` and `htmlFor`, respectively.
## The Transform
JSX transforms from an XML-like syntax into native JavaScript. XML elements and
attributes are transformed into arguments to `React.createElement`.
React JSX transforms from an XML-like syntax into native JavaScript. XML elements, attributes and children are transformed into arguments to `React.createElement`.
```javascript
var Nav;
@ -47,7 +66,11 @@ var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = React.createElement(Nav, {color:"blue"}, React.createElement(Profile, null, "click"));
var app = React.createElement(
Nav,
{color:"blue"},
React.createElement(Profile, null, "click")
);
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
@ -55,72 +78,14 @@ desugars into native JavaScript, and the
[HTML to JSX converter](/react/html-jsx.html) to convert your existing HTML to
JSX.
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows
how to setup compilation.
> Note:
>
> Details about the code transform are given here to increase understanding, but
> your code should not rely on these implementation details.
## React and JSX
React and JSX are independent technologies, but JSX was primarily built with
React in mind. The two valid uses of JSX are:
* To construct instances of React DOM components (`React.DOM.*`).
* To construct instances of composite components created with
`React.createClass()`.
### React DOM Components
To construct a `<div>` is to create a variable that refers to `React.DOM.div`.
```javascript
var div = React.DOM.div;
var app = <div className="appClass">Hello, React!</div>;
```
### React Composite Components
To construct an instance of a composite component, create a variable that
references the class.
```javascript
var MyComponent = React.createClass({/*...*/});
var app = <MyComponent someProperty={true} />;
```
JSX will infer the component's name from the variable assignment and specify
the class's [displayName](/react/docs/component-specs.html#displayName) accordingly.
See [Multiple Components](/react/docs/multiple-components.html) to learn more about using composite components.
If you want to use JSX, the [Getting Started](/react/docs/getting-started.html) guide shows how to setup compilation.
> Note:
>
> Since JSX is JavaScript, identifiers such as `class` and `for` are discouraged
> as XML attribute names. Instead, React DOM components expect attributes like
> `className` and `htmlFor`, respectively.
## DOM Convenience
Having to define variables for every type of DOM element can get tedious
(e.g. `var div, span, h1, h2, ...`). JSX provides a convenience to address this
problem:
```javascript
var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav(null, React.DOM.span(null));
```
> Remember:
>
> JSX simply transforms elements into function calls and has no notion of the
> DOM.
> The JSX expression always evaluates to a ReactElement. The actual
> implementation details may vary. An optimized mode could inline the
> ReactElement as an object literal to bypass the validation code in
> `React.createElement`.
## JavaScript Expressions
@ -133,7 +98,10 @@ pair of curly braces (`{}`) instead of quotes (`""`).
// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = Person({name: window.isLoggedIn ? window.name : ''});
var person = React.createElement(
Person,
{name: window.isLoggedIn ? window.name : ''}
);
```
### Child Expressions
@ -144,7 +112,11 @@ Likewise, JavaScript expressions may be used to express children:
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container(null, window.isLoggedIn ? Nav(null) : Login(null));
var content = React.createElement(
Container,
null,
window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
);
```
### Comments
@ -165,15 +137,6 @@ var content = (
);
```
## Prior Work
JSX is similar to several other JavaScript embedded XML language
proposals/projects. Some of the features of JSX that distinguish it from similar
efforts include:
* JSX is a simple syntactic transform.
* JSX neither provides nor requires a runtime library.
* JSX does not alter or add to the semantics of JavaScript.
JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.
> NOTE:
>
> JSX is similar to HTML, but not exactly the same. See [JSX gotchas](/react/docs/jsx-gotchas.html) for some key differences.

71
docs/02.2-jsx-spread.md

@ -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.

2
docs/02.2-jsx-gotchas.md → docs/02.3-jsx-gotchas.md

@ -2,7 +2,7 @@
id: jsx-gotchas
title: JSX Gotchas
permalink: jsx-gotchas.html
prev: jsx-in-depth.html
prev: jsx-spread.html
next: interactivity-and-dynamic-uis.html
---
Loading…
Cancel
Save