Browse Source

delete old docs

main
petehunt 11 years ago
parent
commit
cb9b0fc3c7
  1. 119
      docs/advanced-components.md
  2. 153
      docs/api.md
  3. 29
      docs/common-questions.md
  4. 73
      docs/component-basics.md
  5. 145
      docs/component-data.md
  6. 85
      docs/component-lifecycle.md
  7. 224
      docs/event-handling.md
  8. 118
      docs/getting-started.md
  9. 95
      docs/jsx-is-not-html.md
  10. 65
      docs/mixins.md
  11. 168
      docs/syntax.md

119
docs/advanced-components.md

@ -1,119 +0,0 @@
---
id: docs-advanced-components
title: Advanced Components
description: How to build advanced composite components.
layout: docs
prev: event-handling.html
next: mixins.html
---
Composite components extend a `ReactCompositeComponent` base class that provides
a very powerful API that makes React flexible and able to easily work with other
libraries and frameworks.
## Lifecycle Methods
Composite components can optionally implement lifecycle methods that are invoked
at various stages in the [component lifecycle](component-lifecycle.html) that
each have unique guarantees.
### Mounting
- `getInitialState(): object` is invoked before a component is mounted.
Stateful components should implement this and return the initial state data.
- `componentWillMount()` is invoked immediately before mounting occurs.
- `componentDidMount(DOMElement rootNode)` is invoked immediately after
mounting occurs. Initialization that requires DOM nodes should go here.
### Updating
- `componentWillReceiveProps(object nextProps)` is invoked when a mounted
component receives new props. This method should be used to compare
`this.props` and `nextProps` to perform state transitions using
`this.setState()`.
- `shouldComponentUpdate(object nextProps, object nextState): boolean` is
invoked when a component decides whether any changes warrant an update to the
DOM. Implement this as an optimization to compare `this.props` with
`nextProps` and `this.state` with `nextState` and return false if React
should skip updating.
- `componentWillUpdate(object nextProps, object nextState)` is invoked
immediately before updating occurs. You cannot call `this.setState()` here.
- `componentDidUpdate(object prevProps, object prevState, DOMElement rootNode)`
is invoked immediately after updating occurs.
### Unmounting
- `componentWillUnmount()` is invoked immediately before a component is
unmounted and destroyed. Cleanup should go here.
## Mounted Methods
_Mounted_ composite components also support the following methods:
- `getDOMNode(): DOMElement` can be invoked on any mounted component in order
to obtain a reference to its rendered DOM node.
- `forceUpdate()` can be invoked on any mounted component when you know that
some deeper aspect of the component's state has changed without using
`this.setState()`.
> Note:
>
> The `DOMElement rootNode` argument of `componentDidMount()` and
> `componentDidUpdate()` is a convenience. The same node can be obtained by
> calling `this.getDOMNode()`.
## Component Refs
A common use case of event callbacks or the lifecycle methods is to operate on a
component returned by `render()`. For example, consider a search component that
should auto-focus the input once mounted:
```javascript
var SearchForm = React.createClass({
render: function() {
return (
<form action={this.props.action}>
<input type="search" placeholder="Search..." />
</form>
);
},
componentDidMount: function(rootNode) {
var searchInput = rootNode.firstChild;
searchInput.focus();
}
});
```
Although this implementation works, it is fragile because `componentDidMount()`
now relies on `render()` returning a particular DOM structure.
React provides a better way for composite components to reference components
that it constructs in its `render()` method through the use of refs. A component
can assign a `ref` to any component it constructs. This will create a reference
to those components on `this.refs`. For example:
```javascript{5,10}
var SearchForm = React.createClass({
render: function() {
return (
<form action={this.props.action}>
<input type="search" placeholder="Search..." ref="searchInput" />
</form>
);
},
componentDidMount: function(rootNode) {
var searchInput = this.refs.searchInput.getDOMNode();
searchInput.focus();
}
});
```
In this example, `this.refs.searchInput` will reference the `<input>` component
and is available in most lifecycle methods and event callbacks. We obtain a
reference to the `<input>`'s DOM node using `getDOMNode()`.
> Note:
>
> If you want to preserve compatibility with Google Closure Compiler's
> property crushing in `ADVANCED_OPTIMIZATIONS` mode, make sure to use string
> literals with `this.refs`.

153
docs/api.md

@ -1,153 +0,0 @@
---
id: docs-api
title: React API
layout: docs
prev: mixins.html
next: jsx-is-not-html.html
---
## React
`React` is the entry point to the React framework. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can `require()` it.
#### React.DOM
`React.DOM` provides all of the standard HTML tags needed to build a React app. You generally don't use it directly; instead, just include it as part of the `/** @jsx React.DOM */` docblock.
#### React.initializeTouchEvents
```javascript
initializeTouchEvents(boolean shouldUseTouch)
```
Configure React's event system to handle touch events on mobile devices.
#### React.autoBind
```javascript
function autoBind(function method)
```
Marks the provided function to be automatically bound to each React component instance created. This allows React components to define automatically bound methods and ensure that when called they will always reference their current instance.
Example:
```javascript
React.createClass({
click: React.autoBind(function(evt) {
this.setState({jumping: true});
}),
render: function() {
// Look: no bind!
return <a onClick={this.click}>Jump</a>;
}
});
```
#### React.createClass
```javascript
function createClass(object specification)
```
Creates a component given a specification. A component implements a `render` method which returns **one single** child. That child may have an arbitrarily deep child structure. One thing that makes components different than a standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.
#### React.renderComponent
```javascript
ReactComponent renderComponent(ReactComponent container, DOMElement mountPoint)
```
Renders a React component into the DOM in the supplied `container`.
If the React component was previously rendered into `container`, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React component.
## AbstractEvent
Your event handlers will be passed instances of `AbstractEvent`, a cross-browser wrapper around the browser's native event. It has the same interface as the browser's native event (such as `stopPropagation()` and `preventDefault()`) except they work exactly the same across all browsers.
If you find that you need the underlying browser event for some reason, simply use the `nativeEvent` attribute to get it.
## ReactComponent
Component classses created by `createClass()` return instances of `ReactComponent` when called. Most of the time when you're using React you're either creating or consuming `ReactComponent`s.
#### getDOMNode
```javascript
DOMElement getDOMNode()
```
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
#### setProps
```javascript
setProps(object nextProps)
```
When you're integrating with an external JavaScript application you may want to signal a change to a React component rendered with `renderComponent()`. Simply call `setProps()` to change its properties and trigger a re-render.
**Note:** This method can only be called on a root-level component. That is, it's only available on the component passed directly to `renderComponent()` and none of its children. If you're inclined to use `setProps()` on a child component, instead take advantage of reactive updates and pass the new prop to the child component when it's created in `render()`.
#### replaceProps
```javascript
replaceProps(object nextProps)
```
Like `setProps()` but deletes any pre-existing props that are not in nextProps.
#### transferPropsTo
```javascript
ReactComponent transferPropsTo(ReactComponent targetComponent)
```
Transfer properties from this component to a target component that have not already been set on the target component. This is usually used to pass down properties to the returned root component. `targetComponent`, now updated with some new props is returned as a convenience.
#### setState
```javascript
setState(object nextState[, function callback])
```
Merges nextState with the current state. This is the primary method you use to trigger UI updates from event handlers and server request callbacks. In addition, you can supply an optional callback function that is executed once `setState` is completed.
**Note:** *NEVER* mutate `this.state` directly. As calling `setState()` afterwards may replace the mutation you made. Treat `this.state` as if it were immutable.
**Note:** `setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value.
**Note**: There is no guarantee of synchronous operation of calls to `setState` and calls may eventually be batched for performance gains.
#### replaceState
```javascript
replaceState(object nextState)
```
Like `setState()` but deletes any pre-existing state keys that are not in nextState.
#### forceUpdate()
```javascript
forceUpdate()
```
If your `render()` method reads from something other than `this.props` or `this.state` you'll need to tell React when it needs to re-run `render()`. Use `forceUpdate()` to cause React to automatically re-render. This will cause `render()` to be called on the component and all of its children but React will only update the DOM if the markup changes.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your application much simpler and more efficient.
```javascript
object getInitialState()
componentWillMount()
componentDidMount(DOMElement domNode)
componentWillReceiveProps(object nextProps)
boolean shouldComponentUpdate(object nextProps, object nextState)
componentWillUpdate(object nextProps, object nextState)
ReactComponent render()
componentDidUpdate(object prevProps, object prevState, DOMElement domNode)
componentWillUnmount()
```
See the [advanced components](advanced-components.html) documentation for more details on these lifecycle methods.

29
docs/common-questions.md

@ -1,29 +0,0 @@
---
id: docs-common-questions
title: Common Questions
layout: docs
prev: tutorial.html
next: syntax.html
---
### What browsers does React support?
React supports the latest two Chrome, Firefox, Safari, and Internet Explorer versions. React can work with Internet Explorer 8 with polyfills.
### How do I get React to support Internet Explorer 8?
React requires ES5 JavaScript shims to run in Internet Explorer 8. Include the [ES5 Shims and shams](https://github.com/kriskowal/es5-shim)
and [console-polyfill)(https://github.com/paulmillr/console-polyfill/) to implement these shims.
### Who uses React?
The [Instagram](http://instagram.com/) website is built entirely in React. The [Facebook](https://www.facebook.com/) website is also increasingly using React, including the common commenting plugin across the site.
### I don't get it. React is confusing!
[This blog post by a member of the React team](http://www.quora.com/Pete-Hunt/Posts/React-Under-the-Hood) talks about some of the reasons
why React is designed the way that it is.
### Can I integrate with other JavaScript libraries?
Absolutely! In fact, we encourage it! See [our GitHub repo](http://github.com/facebook/react/) for a [TodoMVC example using Backbone](https://github.com/facebook/react/tree/master/examples/todomvc-backbone) and a [jQuery + Bootstrap modal demo](https://github.com/facebook/react/tree/master/examples/jquery-bootstrap).

73
docs/component-basics.md

@ -1,73 +0,0 @@
---
id: docs-component-basics
title: Component Basics
description: What are components?
layout: docs
next: component-data.html
prev: syntax.html
---
_Components_ are the basic units of composition in React. Components encapsulate
the logic necessary to take input parameters and render markup. Components can
be rendered into an existing DOM element on the page by using
`React.renderComponent`:
```javascript
// Replaces everything in `document.body` with <div>Hello, world!</div>;
React.renderComponent(<div>Hello, world!</div>, document.body);
```
Keep in mind that `<div>` is **not** a DOM element! Keep reading...
## Types of Components
There are two types of components:
- **Composite Components**
- **DOM Components**
### Composite Components <small>such as `TodoApp` and `Typeahead`.</small>
The majority of your React code will be implementing composite components.
Composite components are higher-level components with custom rendering logic
that may compose other composite components or DOM components.
```javascript
/** @jsx React.DOM */
var LinkButton = React.createClass({
render: function() {
return <a className="btn" />;
}
});
var myButton = <LinkButton />;
```
This example defines a `LinkButton` component class using `React.createClass()`,
and its `render()` method composes the `<a>` DOM component.
### DOM Components <small>such as `div` and `span`.</small>
DOM components are the set of classes that correspond to browser DOM elements.
They are defined in `React.DOM` and can be brought "into scope" by setting
`@jsx React.DOM` in the docblock. See [JSX Syntax](syntax.html) for more
details.
Although `React.DOM` components look like browser DOM elements, they differ in a
few ways:
- All property names, including event handlers, are camelCased.
- JavaScript identifiers should be used, namely `className` and `htmlFor`.
- The `style` prop expects an object instead of a string. The object should map
camelCased style properties to values, e.g. `{backgroundColor: '#fff'}`.
Here is an example of a React link styled as a button with a click handler:
```javascript
/** @jsx React.DOM */
var handleClick = function() {alert('Clicked!');};
var inlineStyle = {textDecoration: 'none'};
var myLink = <a className="btn" onClick={handleClick} style={inlineStyle} />;
```

145
docs/component-data.md

@ -1,145 +0,0 @@
---
id: docs-component-data
title: Component Data
description: How is data passed into a component?
layout: docs
prev: component-basics.html
next: component-lifecycle.html
---
## Props
Components use data to determine what should be rendered. For example:
```javascript
var LikeLink = React.createClass({
render: function() {
var text = this.props.liked ? 'Liked' : 'Like';
return <a>{text}</a>;
}
});
var myLikeLink = <LikeLink liked={false} />;
```
In this example, `LikeLink` takes `liked` as boolean data. This type of data
that is passed in is called a "prop". Examples of props on DOM components
include `className` and `onClick`.
Whenever a component's props change, its `render()` function will be
re-evaluated and the DOM will be updated. React will ensure that the DOM is
always kept up-to-date.
## State
Let's build a small `LikeApp` application that makes use of the `<LikeLink>`
component from above. It should start off unliked and we should be able to like
it by clicking the link:
```javascript
var LikeApp = React.createClass({
render: function() {
var isClicked = false;
return <LikeLink liked={isClicked} onClick={this.handleClick.bind(this)} />;
},
handleClick: function() {
// Somehow update `isClicked`.
}
});
```
This renders a `<LikeLink>` with a click listener. However, it is not clear how
`handleClick` should update `isClicked` to true. `LikeApp` needs a way to store
**state** about whether or not it has been clicked.
### State vs. Props
State is data that is managed _internally_ by a composite component. Like props,
the `render()` function will be re-evaluated whenever state changes. Props and
state differ in that:
- Props are passed in from the creator.
- State is private to and managed by the component.
### Managing State
Let's update our `LikeApp` component using state:
```javascript{2-4,6,10}
var LikeApp = React.createClass({
getInitialState: function() {
return {isClicked: false};
},
render: function() {
var isClicked = this.state.isClicked;
return <LikeLink liked={isClicked} onClick={this.handleClick.bind(this)} />;
},
handleClick: function() {
this.setState({isClicked: true});
}
});
```
There's a lot going on here, so let's work our way from top to bottom:
- `getInitialState()` describes what state data looks like when the component
is created.
- In `render()`, state data can be accessed via `this.state`.
- When the link is clicked, we update state using `setState()`.
Now when we click the link, the `<LikeLink>` will get updated, right? Wrong.
## Transferring Props
If you have been following carefully, you may have noticed that although we pass
a click handler into `<LikeLink>` as a prop, `LikeLink` does not do anything
with `this.props.onClick`! Let's fix that.
```javascript{4}
var LikeLink = React.createClass({
render: function() {
var text = this.props.liked ? 'Liked' : 'Like';
return <a onClick={this.props.onClick}>{text}</a>;
}
});
```
Although this works, realize that this would quickly become tedious if we wanted
to also transfer `href`, `title`, `target`, and other events from `this` to the
rendered `<a>`. React provides a convenience method, `transferPropsTo()`, for
transferring props:
```javascript{4}
var LikeLink = React.createClass({
render: function() {
var text = this.props.liked ? 'Liked' : 'Like';
return this.transferPropsTo(<a>{text}</a>);
}
});
```
This will transfer all props from `this` to the specified component (including
`onClick`).
## Summary
Now we are done. `LikeApp` renders an unliked link which, when clicked, will:
1. Update the internal state of `LikeApp`.
2. Change the props passed into `LikeLink`.
3. Change the return value of `render()`.
4. Trigger an update to the DOM.
It's worth noting that React will handle new return values of `render()` by
making the minimal set of mutations necessary to bring the DOM up-to-date. In
this case, only the `textContent` of the rendered link will be mutated.
In summary:
- Props are passed in whereas state is managed internally by a component.
- Never mutate `this.props` or `this.state`. You should pass props into other
components and mutate state using `setState()`.
- State is private. Never read `state` or call `setState()` on
anything but `this`.
- Whenever props or state changes, `render()` will be re-evaluated and the DOM
updated. Also, `render()` should not depend on anything besides `this.props`
and `this.state`.

85
docs/component-lifecycle.md

@ -1,85 +0,0 @@
---
id: docs-component-lifecycle
title: Component Lifecycle
description: What happens when I render a React component?
layout: docs
prev: component-data.html
next: event-handling.html
---
## Mounting
[We have previously seen](component-basics.html) how to render components into
existing DOM elements on the page:
```javascript
React.renderComponent(<div>Hello, world!</div>, document.body);
```
In this one simple line, we have accomplished the following:
- A `<div>` (defined by `React.DOM.div`) component is instantiated.
- The component is **mounted** into `document.body`.
**Mounting** is the process of initializing a React component by creating its
DOM nodes and inserting them into a supplied container node.
At this point, the entire page consists of a single `<div>` with "Hello,
world!".
## Updating
Let's add a second call to `React.renderComponent()` after three
seconds:
```javascript{2-4}
React.renderComponent(<div>Hello, world!</div>, document.body);
setTimeout(function() {
React.renderComponent(<div>Goodbye, world.</div>, document.body);
}, 3000);
```
The second call to `React.renderComponent()` will trigger the following:
- The `<div>` component will check the new props to see if anything changed.
- The set of changes are used to **update** the DOM node as necessary.
**Updating** is the process of mutating the rendered DOM nodes and occurs
whenever either props or state has changed. This ensures that the rendered DOM
is consistent with the data.
## Unmounting
Let's add one final call to `React.renderComponent()` after another three
seconds:
```javascript{5-7}
React.renderComponent(<div>Hello, world!</div>, document.body);
setTimeout(function() {
React.renderComponent(<div>Goodbye, world.</div>, document.body);
}, 3000);
setTimeout(function() {
React.renderComponent(<img src="/images/fin.png" />, document.body);
}, 6000);
```
The third call to `React.renderComponent()` will trigger the following:
- An `<img>` (defined by `React.DOM.img`) component is instantiated.
- React will compare the `<div>` component with the `<img>` component.
- Since the component class is different, the `<div>` component will be
**unmounted**.
- The `<img>` component will then be mounted into `document.body`.
**Unmounting** is the process of releasing resources that have been allocated by
a component. This allows user interfaces built with React to live long without
memory leaks.
Components can also be unmounted using
`React.unmountAndReleaseReactRootNode()`:
```javascript
React.unmountAndReleaseReactRootNode(document.body);
```
This will unmount any components mounted immediately within `document.body`.

224
docs/event-handling.md

@ -1,224 +0,0 @@
---
id: docs-event-handling
title: Event Handling
description: How do events work with React components?
layout: docs
prev: component-lifecycle.html
next: advanced-components.html
---
Events in React work the way they do with HTML, except the event names are
camelCased.
```javascript
var Clicker = React.createClass({
render: function() {
return <span onClick={this.handleClick}>Click me!</span>;
},
handleClick: function(event) {
alert('You clicked me!');
}
});
```
When `<Clicker>` is clicked, the `handleClick()` function will get fired. Under
the hood, React uses top-level event delegation to achieve high performance.
## Automatically Binding Callbacks
Just like any callback in JavaScript, if you want to refer to the component as
`this` from the callback, you need to bind the callback to the component:
```javascript{3}
var Clicker = React.createClass({
render: function() {
var handleClick = this.handleClick.bind(this);
return <span onClick={handleClick}>Click me!</span>;
},
handleClick: function(event) {
alert(this.ALERT_MESSAGE);
},
ALERT_MESSAGE: 'You clicked me!'
});
```
React provides a convenient and _efficient_ way to bind methods using
`React.autoBind()`:
```javascript{3,5-7}
var Clicker = React.createClass({
render: function() {
return <span onClick={this.handleClick}>Click me!</span>;
},
handleClick: React.autoBind(function(event) {
alert(this.ALERT_MESSAGE);
}),
ALERT_MESSAGE: 'You clicked me!'
});
```
> Note:
>
> Binding a function allocates memory to create a new bound function. Since
> `render()` may be invoked many times, it is a bad place to bind functions.
> `React.autoBind()` sidesteps this issue by only binding once at instantiation
> time.
## DOM Events
React uses [top-level event delegation](http://davidwalsh.name/event-delegate)
to achieve high performance when implementing DOM events. For each type of DOM
event, React adds a single top-level listener and determines which event
handlers to execute by simulating event capturing and bubbling.
DOM event handlers are called with a normalized `AbstractEvent` object that has
cross-browser compatible implementations of `stopPropagation` and
`preventDefault()`. If you need access to the raw browser event, you can use the
`nativeEvent` property.
> Note:
>
> The `AbstractEvent` object is JSON serializable so that React applications can
> be executed inside web workers.
### Touch Events
If you want to use touch events, you must configure React's event system to
initialize them:
```javascript
// Invoke before calling `React.renderComponent()`.
React.initializeTouchEvents(true);
```
## Custom Events
Notice that event listeners are attached by simply passing them into components
as props. For DOM components, events are handled using top-level event
delegation. For composite components, event handling is up to the component's
implementation.
Here is an example of a toggle link that fires a custom `onToggle` event:
```javascript
var ToggleLink = React.createClass({
getInitialState: function() {
return {isEnabled: false};
},
render: function() {
return <a onClick={this.handleClick}>Toggle</a>;
},
handleClick: React.autoBind(function() {
var willEnable = !this.state.isEnabled;
if (this.props.onToggle) {
this.props.onToggle(willEnable)
}
this.setState({isEnabled: willEnable});
})
});
var handleToggle = function(enabled) {
alert(enabled ? 'Enabled.' : 'Disabled.');
};
var myToggleLink = <ToggleLink onToggle={handleToggle} />;
```
### Common Patterns
With React your event handlers should be quite small. Large event handlers may
be symptomatic of code that should be moved into helpers or into `render()`.
Here are some common usage patterns for event handlers.
#### Updating State
The most common thing to do in response to a user action is to call
`this.setState()` to update the component's state, which will in turn trigger
an update to the rendered component.
#### Server Requests
Many event handlers will issue a server request to read or write some data in
response to an event. The response handler for the request will often call
`this.setState()`.
#### Invoke a Callback
Your component will often be a small, reusable building block that does not know
how to respond to a user action. In these situations, we delegate the
responsibility to the owner by exposing a handler on `this.props`. This is what
the `ToggleLink` example above is doing.
#### Inter-component Communication
A common scenario involves communicating to **Component A** that a user action
has occurred on **Component B**. To solve this problem, a common parent to
both components should listen for the event on **Component B**, update its
internal state, and pass that data into **Component A**.
For example, say we have two components: **Clicker**, a component that fires an
`onCountChange` custom event, and **ClickCountLabel**, a component that displays
the number of clicks that have happened:
```javascript
var Clicker = React.createClass({
getInitialState: function() {
return {count: 0};
},
render: function() {
return <span onClick={this.handleClick}>Click me!</span>;
},
handleClick: React.autoBind(function() {
this.setState({count: this.state.count + 1});
if (this.props.onCountChange) {
this.props.onCountChange(this.state.count);
}
})
});
var ClickCountLabel = React.createClass({
render: function() {
return <p>You have clicked <strong>{this.props.count}</strong> times.</p>;
}
});
var ClickApp = React.createClass({
render: function() {
var count = 0;
return (
<div>
<Clicker onCountChange={this.handleCountChange} />
<ClickCountLabel count={count} />
</div>
);
},
handleCountChange: React.autoBind(function(count) {
// Somehow update `count`.
})
});
```
In order to communicate the click count from `Clicker` to `ClickCountLabel`, we
modify `ClickApp` to maintain state that will be passed into `ClickCountLabel`:
```javascript{2-4,6,15}
var ClickApp = React.createClass({
getInitialState: function() {
return {count: 0};
},
render: function() {
var count = this.state.count;
return (
<div>
<Clicker onCountChange={this.handleCountChange} />
<ClickCountLabel count={count} />
</div>
);
},
handleCountChange: React.autoBind(function(count) {
this.setState({count: count});
})
});
```
Now when `Clicker` fires the `onCountChange` event, the `ClickCountLabel` will
get updated!

118
docs/getting-started.md

@ -1,118 +0,0 @@
---
id: docs-getting-started
title: Getting Started
layout: docs
next: tutorial.html
---
## JSFiddle
The easiest way to start hacking on React is using the following JSFiddle Hello Worlds
* **[React JSFiddle](http://jsfiddle.net/vjeux/kb3gN/)**
* [React JSFiddle without JSX](http://jsfiddle.net/vjeux/VkebS/)
## Starter Kit
Download the starter kit to get started.
<div class="buttons-unit downloads">
<a href="/react/downloads/react-{{site.react_version}}.zip" class="button">
Download Starter Kit {{site.react_version}}
</a>
</div>
In the root directory of the starter kit, create a `helloworld.html` with the following contents.
```html
<!DOCTYPE html>
<html>
<head>
<script src="build/react.min.js"></script>
<script src="build/JSXTransformer.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/jsx">
/** @jsx React.DOM */
React.renderComponent(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
</script>
</body>
</html>
```
The XML syntax inside of JavaScript is called JSX; check out the [JSX syntax](syntax.html) to learn more about it. In order to translate it to vanilla JavaScript we use `<script type="text/jsx">` and include `JSXTransformer.js` to actually perform the transformation in the browser.
### Separate File
Your React JSX file can live in a separate file. Create the following `src/helloworld.js`.
```javascript
/** @jsx React.DOM */
React.renderComponent(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
```
Then reference it from `helloworld.html`:
```html{10}
<script type="text/jsx" src="src/helloworld.js"></script>
```
### Offline Transform
First install the command-line tools (requires [npm](http://npmjs.org/)):
```
npm install -g react-tools
```
Then, translate your `src/helloworld.js` file to plain JavaScript:
```
jsx --watch src/ build/
```
The file `build/helloworld.js` is autogenerated whenever you make a change.
```javascript{3}
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, 'Hello, world!'),
document.getElementyById('example')
);
```
> Note:
>
> The comment parser is very strict right now, in order for it to pick up the `@jsx` modifier, two conditions are required. The `@jsx` comment block must be the first comment on the file. The comment must start with `/**` (`/*` and `//` will not work). If the parser can't find the `@jsx` comment, it will output the file without transforming it.
Update your HTML file as below:
```html{6,10}
<!DOCTYPE html>
<html>
<head>
<title>Hello React!</title>
<script src="build/react.min.js"></script>
<!-- No need for JSXTransformer! -->
</head>
<body>
<div id="example"></div>
<script src="build/helloworld.js"></script>
</body>
</html>
```
## Want CommonJS?
If you want to use React within a module system, [fork our repo](http://github.com/facebook/react), `npm install` and run `grunt`. A nice set of CommonJS modules will be generated. Our `jsx` build tool can be integrated into most packaging systems (not just CommonJS) quite easily.
## Next Steps
Check out [the tutorial](tutorial.html) and the other examples in the `/examples` directory to learn more. Good luck, and welcome!

95
docs/jsx-is-not-html.md

@ -1,95 +0,0 @@
---
id: docs-jsx-is-not-html
title: JSX is not HTML
description: Differences between JSX and HTML.
layout: docs
prev: api.html
---
JSX looks like HTML but there are some important differences you may run into.
## Whitespace removal
JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all whitespace between two curly braces expressions. If you want to have whitespace, simply add `{' '}`.
```javascript
<div>{this.props.name} {' '} {this.props.surname}</div>
```
Follow [Issue #65](https://github.com/facebook/react/issues/65) for discussion on this behavior.
## HTML Entities
You can insert HTML entities within literal text in JSX:
```javascript
<div>First &middot; Second</div>
```
If you want to display an HTML entity within dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default.
```javascript
// Bad: It displays "First &middot; Second"
<div>{'First &middot; Second'}</div>
```
There are various ways to work-around this issue. The easiest one is to write unicode character directly in Javascript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
```javascript
<div>{'First · Second'}</div>
```
A safer alternative is to find the [unicode number corresponding to the entity](http://www.fileformat.info/info/unicode/char/b7/index.htm) and use it inside of a JavaScript string.
```javascript
<div>{'First \u00b7 Second'}</div>
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
```
You can use mixed arrays with strings and JSX elements.
```javascript
<div>{['First ', <span>&middot;</span>, ' Second']}</div>
```
As a last resort, you always have the ability to insert raw HTML.
```javascript
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First &middot; Second'}} />
```
## Comments
JSX supports both single-line and multi-line JavaScript comments within a tag declaration:
```javascript
<div // This is a single-line comment:
/*
And a multi-line
comment
*/
/>
```
As of React 0.3, there is no good way to insert comments within the children section. [Issue #82](https://github.com/facebook/react/issues/82) is tracking progress to enable the following:
```javascript
// Note: This is not implemented yet!
<div>
{/* This is a comment */}
</div>
```
## Custom HTML Attributes
If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`.
```javascript
<div data-custom-attribute="foo" />
```
[Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly.
```javascript
<div aria-hidden={true} />
```

65
docs/mixins.md

@ -1,65 +0,0 @@
---
id: docs-mixins
title: Mixins
layout: docs
prev: advanced-components.html
next: api.html
---
Mixins allow code to be shared between multiple React components. They are pretty similar to mixins
in Python or traits in PHP. Let's look at a simple example:
```javascript
var MyMixin = {
getMessage: function() {
return 'hello world';
}
};
var MyComponent = React.createClass({
mixins: [MyMixin],
render: function() {
return <div>{this.getMessage()}</div>;
}
});
```
A class can use multiple mixins, but no two mixins can define the same method. Two mixins can, however,
implement the same [lifecycle method](component-lifecycle.html). In this case, each implementation will be invoked one after another.
The only exception is the `shouldComponentUpdate` lifecycle method. This method may only be implemented once
(either by a mixin or by the component).
```javascript
var Mixin1 = {
componentDidMount: function() {
console.log('Mixin1.componentDidMount()');
}
};
var Mixin2 = {
componentDidMount: function() {
console.log('Mixin2.componentDidMount()');
}
};
var MyComponent = React.createClass({
mixins: [Mixin1, Mixin2],
render: function() {
return <div>hello world</div>;
}
});
```
When `MyComponent` is mounted into the page, the following text will print to the console:
```
Mixin1.componentDidMount()
Mixin2.componentDidMount()
```
## When should you use mixins?
In general, add a mixin whenever you want a component to share some utility methods, public interface,
or lifecycle behavior. Often it's appropriate to use them as you would use a superclass in another OOP language.

168
docs/syntax.md

@ -1,168 +0,0 @@
---
id: docs-syntax
title: JSX Syntax
description: Writing JavaScript with XML syntax.
layout: docs
prev: common-questions.html
next: component-basics.html
---
JSX is a JavaScript XML syntax transform recommended (but not required) for use
with React.
## Why JSX?
First of all, **don't use JSX if you don't like it!**
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:
```javascript
var link = React.DOM.a({href: 'http://facebook.github.io/react'}, 'React');
```
We recommend using JSX for many reasons:
- 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.
## The Transform
JSX transforms XML-like syntax into native JavaScript. It turns XML elements and
attributes into function calls and objects, respectively.
```javascript
var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = Nav({color:'blue'}, null);
```
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
JSX also allows specifying children using XML syntax:
```javascript
var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = Nav({color:'blue'}, Profile(null, 'click'));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desugars into native JavaScript.
If you want to use JSX, the [Getting Started](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 Component 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} />;
```
See [Component Basics](component-basics.html) to learn more about components.
> 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 by allowing you to specify a variable in an `@jsx` docblock field. JSX
will use that field to find DOM components.
```javascript
/**
* @jsx React.DOM
*/
var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav(null, React.DOM.span(null, null));
```
> Remember:
>
> JSX simply transforms elements into function calls and has no notion of the
> DOM. The docblock parameter is only a convenience to resolve the most commonly
> used elements. In general, JSX has no notion of the DOM.
## JavaScript Expressions
#### Attribute Expressions
To use a JavaScript expression as an attribute value, wrap the expression in a
pair of curly braces (`{}`) instead of quotes (`""`).
```javascript
// Input (JSX):
var person = <Person name={window.isLoggedIn ? window.name : ''} />;
// Output (JS):
var person = Person({name: window.isLoggedIn ? window.name : ''});
```
#### Child Expressions
Likewise, JavaScript expressions may be used to express children:
```javascript
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container(null, window.isLoggedIn ? Nav(null, null) : Login(null, null));
```
## Tooling
Beyond the compilation step, JSX does not require any special tools.
- Many editors already include reasonable support for JSX (Vim, Emacs js2-mode).
- Linting provides accurate line numbers after compiling without sourcemaps.
- Elements use standard scoping so linters can find usage of out-of-scope
components.
## 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.
Loading…
Cancel
Save