Compare commits

...

33 Commits

Author SHA1 Message Date
Pete Hunt
f7c56d77df Update syntax.md
Some inconsistencies pointed out in FB comments
(cherry picked from commit b6451be582)
2013-07-11 15:59:03 -07:00
Cheng Lou
5cdc55664d Emphasis on single child.
(cherry picked from commit 858377946f)
2013-07-11 15:58:53 -07:00
Paul O’Shannessy
d098ad7222 New blog post: Props in v0.4
(cherry picked from commit 607de16d82)
2013-07-11 15:53:15 -07:00
Vjeux
67fc4266f4 Community Round-up #4
(cherry picked from commit 2246f530af)
2013-07-03 18:36:24 -07:00
Paul O’Shannessy
fc84582daa Blog: Autobind by Default
Kicking off the series of posts previewing v0.4

(cherry picked from commit 9ca7c9631a)
2013-07-02 13:06:46 -07:00
Mathieu M-Gosselin
759d387649 Changed JSON data in the tutorial to use double quotes for strings.
(cherry picked from commit 703c825196)
2013-06-28 09:48:45 -07:00
Christopher Chedeau
31838ac88f Add @jsx common parser issues in the docs
Update getting-started.md

(cherry picked from commit 418c1fc427)
2013-06-28 09:48:45 -07:00
Vjeux
636a1de1de Add link roundup
(cherry picked from commit d4c7991aee)
2013-06-28 09:48:45 -07:00
Vjeux
bc7c9166e5 Community Roundup #3 2013-06-27 13:43:50 -07:00
Paul O’Shannessy
65c3942889 Blogpost & changelog for v0.3.3
(cherry picked from commit 18352090e7)
2013-06-21 10:59:22 -07:00
Paul O’Shannessy
df17c7efe3 v0.3.3 2013-06-20 15:14:18 -07:00
CommitSyncScript
2af5be4c4c Support rendering different components into same node
var container = ...; // some DOM node
React.renderComponent(<div />, container);
React.renderComponent(<span />, container);

This should replace the rendered <div> with a <span>, effectively
reconciling at the root level.
(cherry picked from commit 100af48f53)
2013-06-20 10:57:26 -07:00
Paul O’Shannessy
e105cb56e7 Improve JSXTransformer
The biggest improvement is that we'll now insert each parsed JSX script
back into a `<script>` tag with the body set. This allows the browser to
execute these scripts normally. Using `Function(functionBody)` or
`eval(functionBody)` both execute in window scope, but `var` assignments
don't actually get set on window (unlike everywhere else).

I also did some cleanup to make the code a little bit more readable.
In my minimal test cases this didn't break anything (scripts loaded in
the right order).
(cherry picked from commit c79a59b599)
2013-06-19 17:29:05 -07:00
Paul O’Shannessy
9757f0a7e7 Use github tarball link for esprima dependency
It turns out that (at least for local development) npm has a long
standing bug where it doesn't recognize changing dependencies stored as
git urls (see https://github.com/isaacs/npm/issues/1727). Luckily npm
understand tarballs and GitHub provides tarballs for every commit, so
the workaround is easy, though unfortunate.
(cherry picked from commit bd044fc919)
2013-06-19 17:29:05 -07:00
Ben Newman
2d677b78ba Upgrade Recast to 0.4.8 to fix options.writeback bug.
Bug introduced by: https://github.com/benjamn/recast/commit/e913b22f8f
Bug fixed by: https://github.com/benjamn/recast/commit/170e18091e
(cherry picked from commit 2383fd8813)
2013-06-19 17:29:04 -07:00
Ben Newman
3624afaade Upgrade Commoner and Recast to latest versions.
The Commoner upgrade is a big one because it makes bin/jsx no longer
rewrite module identifiers to be relative by default, which should
reduce confusion for people trying to use it as a standalone
transformer.

Closes #80.
(cherry picked from commit 15360056bd)
2013-06-19 17:29:04 -07:00
Paul O’Shannessy
0fbf7ad4e5 Ignore .module-cache directories
(cherry picked from commit 5bd449c157)
2013-06-19 17:29:04 -07:00
Ben Newman
9b810bd7b9 Cache modules for jsx grunt tasks in react-tools/.module-cache.
As of Commoner v0.6.11, the default is to put the cache files in
output/.module-cache, which used to be build/modules/.module-cache
before this commit. That still happens when you run bin/jsx directly,
just not for grunt tasks anymore.

The module cache needs to be cleared much less often than
build/modules, so it doesn't make sense to throw away all that work.
(cherry picked from commit 880ada0a1c)
2013-06-19 17:29:04 -07:00
Vjeux
1c486c40d0 Community Roundup #2 2013-06-19 12:33:14 -07:00
Christopher Chedeau
376045b401 Fix dangerouslySetInnerHTML 2013-06-19 12:32:50 -07:00
Paul O’Shannessy
267c97b14f Use absolute URLs for FB comments box 2013-06-18 10:21:28 -07:00
petehunt
9eed65d7db Update jsx-is-not-html.md 2013-06-17 17:18:48 -07:00
Ben Alpert
f09a068c74 Link to my own blog 2013-06-17 17:18:42 -07:00
Greg Roodt
8eb46be792 Minor grammar. 2013-06-17 17:18:36 -07:00
Greg Roodt
7bbe9baf6f Minor typo. 2013-06-17 17:18:29 -07:00
Greg Roodt
da9ddffb3a Update tutorial.md
The ajax call happens every 5 seconds, not every 60 seconds.
2013-06-17 17:18:23 -07:00
Vjeux
388c8a505d Adding JSX pitfalls section in the docs 2013-06-17 17:17:20 -07:00
Vjeux
dadb3f79cd Facebook comments integration on Docs and Blog 2013-06-17 17:17:07 -07:00
Vjeux
dcd85395fd Using markdown instead of html 2013-06-12 14:05:33 -07:00
Vjeux
c2b4d338ab Integrate twitter in the support page 2013-06-12 14:05:21 -07:00
petehunt
b148b1235e Fixed width/height on React logo 2013-06-12 14:00:33 -07:00
Vjeux
83e1dc5618 Community round-up blog post 2013-06-12 14:00:22 -07:00
jordow
92b795da6a Make todo example shorter and not rely on the DOM. 2013-06-07 15:40:09 -07:00
37 changed files with 666 additions and 100 deletions

2
.gitignore vendored
View File

@@ -6,11 +6,13 @@ static
.grunt
_SpecRunner.html
build/
.module-cache
*.gem
docs/code
docs/_site
docs/.sass-cache
docs/css/react.css
docs/js/.module-cache
docs/js/JSXTransformer.js
docs/js/react.min.js
docs/js/docs.js

View File

@@ -5,7 +5,7 @@ description: A JavaScript library for building user interfaces
redcarpet:
extensions:
- fenced_code_blocks
react_version: 0.3.2
react_version: 0.3.3
pygments: true
exclude:
- Gemfile

View File

@@ -356,6 +356,22 @@ section.black content {
padding-bottom: 18px;
}
/**
* Blog
*/
.blogContent {
padding-top: 20px;
blockquote {
padding: 5px 15px;
margin: 20px 0;
background-color: #f8f5ec;
border-left: 5px solid #f7ebc6;
}
}
/**
* Docs
*/
@@ -495,6 +511,10 @@ p {
margin-bottom: 20px;
}
figure {
text-align: center;
}
.inner-content {
float: right;
width: $skinnyContentWidth;
@@ -658,3 +678,7 @@ p code {
padding-top: 0;
}
}
.post {
margin-bottom: 30px;
}

View File

@@ -21,4 +21,11 @@
<li><a href="/react/docs/api.html"{% if page.id == 'docs-api' %} class="active"{% endif %}>API</a></li>
</ul>
</div>
<div class="nav-docs-section">
<h3>Appendix</h3>
<ul>
<li><a href="/react/docs/jsx-is-not-html.html"{% if page.id == 'docs-jsx-is-not-html' %} class="active"{% endif %}>JSX is not HTML</a></li>
</ul>
</div>
</div>

View File

@@ -6,48 +6,38 @@ var TODO_COMPONENT = "\
/** @jsx React.DOM */\n\
var TodoList = React.createClass({\n\
render: function() {\n\
var items = this.props.items.map(function(item) {\n\
return <li>{item}</li>;\n\
});\n\
return <ul>{items}</ul>;\n\
var createItem = function(itemText) {\n\
return <li>{itemText}</li>;\n\
};\n\
return <ul>{this.props.items.map(createItem)}</ul>;\n\
}\n\
});\n\
\n\
var TodoCreate = React.createClass({\n\
handleSubmit: React.autoBind(function() {\n\
var textInput = this.refs.textInput.getDOMNode();\n\
this.props.onCreate(textInput.value);\n\
textInput.value = '';\n\
return false;\n\
}),\n\
render: function() {\n\
return (\n\
<form onSubmit={this.handleSubmit}>\n\
<input type=\"text\" ref=\"textInput\" />\n\
<button>Add</button>\n\
</form>\n\
);\n\
}\n\
});\n\
\n\
var TodoApp = React.createClass({\n\
getInitialState: function() {\n\
return {items: []};\n\
return {items: [], text: ''};\n\
},\n\
onKey: function(e) {\n\
this.setState({text: e.target.value});\n\
},\n\
handleSubmit: function(e) {\n\
e.preventDefault();\n\
var nextItems = this.state.items.concat([this.state.text]);\n\
var nextText = '';\n\
this.setState({items: nextItems, text: nextText});\n\
},\n\
onItemCreate: React.autoBind(function(value) {\n\
this.setState({items: this.state.items.concat([value])});\n\
}),\n\
render: function() {\n\
return (\n\
<div>\n\
<h3>TODO</h3>\n\
<TodoList items={this.state.items} />\n\
<TodoCreate onCreate={this.onItemCreate} />\n\
<form onSubmit={this.handleSubmit.bind(this)}>\n\
<input onKeyUp={this.onKey.bind(this)} value={this.state.text} />\n\
<button>{'Add #' + (this.state.items.length + 1)}</button>\n\
</form>\n\
</div>\n\
);\n\
}\n\
});\n\
\n\
React.renderComponent(<TodoApp />, mountNode);\
";

View File

@@ -35,7 +35,7 @@
<div class="nav-main">
<div class="wrap">
<a class="nav-home" href="/react/index.html">
<img class="nav-logo" alt="" src="/react/img/logo_small.png">
<img class="nav-logo" alt="" src="/react/img/logo_small.png" width="38" height="38">
React
</a>
<ul class="nav-site">
@@ -72,6 +72,7 @@
<div class="right">&copy; 2013 Facebook Inc.</div>
</footer>
</div>
<div id="fb-root"></div>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
@@ -79,7 +80,16 @@
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-41298772-1', 'facebook.github.io');
ga('send', 'pageview');
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=623268441017527";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
</body>
</html>

View File

@@ -19,5 +19,7 @@ sectionid: docs
<a class="docs-next" href="/react/docs/{{ page.next }}">Next &rarr;</a>
{% endif %}
</div>
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
</div>
</section>

View File

@@ -3,7 +3,7 @@ layout: default
sectionid: blog
---
<section class="content wrap documentationContent">
<section class="content wrap blogContent">
{% include nav_blog.html %}
<div class="inner-content">
<h1>{{ page.title }}</h1>
@@ -14,5 +14,8 @@ sectionid: blog
<div class="post">
{{ content }}
</div>
<div class="fb-like" data-send="true" data-width="650" data-show-faces="false"></div>
<div class="fb-comments" data-width="650" data-num-posts="10" data-href="{{ site.url }}{{ site.baseurl }}{{ page.url }}"></div>
</div>
</section>

View File

@@ -0,0 +1,48 @@
---
title: "Community Round-up #1"
layout: post
author: Vjeux
---
React was open sourced two weeks ago and it's time for a little round-up of what has been going on.
## Khan Academy Question Editor
It looks like [Ben Alpert](http://benalpert.com/) is the first person outside of Facebook and Instagram to push React code to production. We are very grateful for his contributions in form of pull requests, bug reports and presence on IRC ([#reactjs on Freenode](irc://chat.freenode.net/reactjs)). Ben wrote about his experience using React:
> I just rewrote a 2000-line project in React and have now made a handful of pull requests to React. Everything about React I've seen so far seems really well thought-out and I'm proud to be the first non-FB/IG production user of React.
>
> The project that I rewrote in React (and am continuing to improve) is the Khan Academy question editor which content creators can use to enter questions and hints that will be presented to students:
> <figure>[![](/react/img/blog/khan-academy-editor.png)](http://benalpert.com/2013/06/09/using-react-to-speed-up-khan-academy.html)</figure>
>
> [Read the full post...](http://benalpert.com/2013/06/09/using-react-to-speed-up-khan-academy.html)
## Pimp my Backbone.View (by replacing it with React)
[Paul Seiffert](https://blog.mayflower.de/) wrote a blog post that explains how to integrate React into Backbone applications.
> React has some interesting concepts for JavaScript view objects that can be used to eliminate this one big problem I have with Backbone.js.
>
> As in most MVC implementations (although React is probably just a VC implementation), a view is one portion of the screen that is managed by a controlling object. This object is responsible for deciding when to re-render the view and how to react to user input. With React, these view-controllers objects are called components. A component knows how to render its view and how to handle to the user's interaction with it.
>
> The interesting thing is that React is figuring out by itself when to re-render a view and how to do this in the most efficient way.
>
> [Read the full post...](https://blog.mayflower.de/3937-Backbone-React.html)
## Using facebook's React with require.js
[Mario Mueller](http://blog.xenji.com/) wrote a menu component in React and was able to easily integrate it with require.js, EventEmitter2 and bower.
> I recently stumbled upon facebook's React library, which is a Javascript library for building reusable frontend components. Even if this lib is only at version 0.3.x it behaves very stable, it is fast and is fun to code. I'm a big fan of require.js, so I tried to use React within the require.js eco system. It was not as hard as expected and here are some examples and some thoughts about it.
>
> [Read the full post...](http://blog.xenji.com/2013/06/facebooks-react-require-js.html)
## Origins of React
[Pete Hunt](http://www.petehunt.net/blog/) explained what differentiates React from other JavaScript libraries in [a previous blog post](http://facebook.github.io/react/blog/2013/06/05/why-react.html). [Lee Byron](http://leebyron.com/) gives another perspective on Quora:
> React isn't quite like any other popular Javascript libraries, and it solves a very specific problem: complex UI rendering. It's also intended to be used along side many other popular libraries. For example, React works well with Backbone.js, amongst many others.
>
> React was born out of frustrations with the common pattern of writing two-way data bindings in complex MVC apps. React is an implementation of one-way data bindings.
>
> [Read the full post...](http://www.quora.com/React-JS-Library/How-is-Facebooks-React-JavaScript-library/answer/Lee-Byron?srid=3DcX)

View File

@@ -0,0 +1,71 @@
---
title: "Community Round-up #2"
layout: post
author: Vjeux
---
Since the launch we have received a lot of feedback and are actively working on React 0.4. In the meantime, here are the highlights of this week.
## Some quick thoughts on React
[Andrew Greig](http://www.andrewgreig.com/) made a blog post that gives a high level description of what React is.
> I have been using Facebooks recently released Javascript framework called React.js for the last few days and have managed to obtain a rather high level understanding of how it works and formed a good perspective on how it fits in to the entire javascript framework ecosystem.
>
> Basically, React is not an MVC framework. It is not a replacement for Backbone or Knockout or Angular, instead it is designed to work with existing frameworks and help extend their functionality.
>
> It is designed for building big UIs. The type where you have lots of reusable components that are handling events and presenting and changing some backend data. In a traditional MVC app, React fulfils the role of the View. So you would still need to handle the Model and Controller on your own.
>
> I found the best way to utilise React was to pair it with Backbone, with React replacing the Backbone View, or to write your own Model/Data object and have React communicate with that.
>
> [Read the full post...](http://www.andrewgreig.com/637/)
## React and Socket.IO Chat Application
[Danial Khosravi](http://danialk.github.io/) made a real-time chat application that interacts with the back-end using Socket.IO.
> A week ago I was playing with AngularJS and [this little chat application](https://github.com/btford/angular-socket-io-im) which uses socket.io and nodejs for realtime communication. Yesterday I saw a post about ReactJS in [EchoJS](http://www.echojs.com/) and started playing with this UI library. After playing a bit with React, I decided to write and chat application using React and I used Bran Ford's Backend for server side of this little app.
> <figure>[![](/react/img/blog/chatapp.png)](http://danialk.github.io/blog/2013/06/16/reactjs-and-socket-dot-io-chat-application/)</figure>
>
> [Read the full post...](http://danialk.github.io/blog/2013/06/16/reactjs-and-socket-dot-io-chat-application/)
## React and Other Frameworks
[Pete Hunt](http://www.petehunt.net/blog/) wrote an answer on Quora comparing React and Angular directives. At the end, he explains how you can make an Angular directive that is in fact being rendered with React.
> To set the record straight: React components are far more powerful than Angular templates; they should be compared with Angular's directives instead. So I took the first Google hit for "AngularJS directive tutorial" (AngularJS Directives Tutorial - Fundoo Solutions), rewrote it in React and compared them. [...]
>
> We've designed React from the beginning to work well with other libraries. Angular is no exception. Let's take the original Angular example and use React to implement the fundoo-rating directive.
>
> [Read the full post...](http://www.quora.com/Pete-Hunt/Posts/Facebooks-React-vs-AngularJS-A-Closer-Look)
In the same vein, [Markov Twain](https://twitter.com/markov_twain/status/345702941845499906) re-implemented the examples on the front-page [with Ember](http://jsbin.com/azihiw/2/edit) and [Vlad Yazhbin](https://twitter.com/vla) re-implemented the tutorial [with Angular](http://jsfiddle.net/vla/Cdrse/).
## Web Components: React & x-tags
Mozilla and Google are actively working on Web Components. [Vjeux](http://blog.vjeux.com/) wrote a proof of concept that shows how to implement them using React.
> Using [x-tags](http://www.x-tags.org/) from Mozilla, we can write custom tags within the DOM. This is a great opportunity to be able to write reusable components without being tied to a particular library. I wrote [x-react](https://github.com/vjeux/react-xtags/) to have them being rendered in React.
> <figure>[![](/react/img/blog/xreact.png)](http://blog.vjeux.com/2013/javascript/custom-components-react-x-tags.html)</figure>
>
> [Read the full post...](http://blog.vjeux.com/2013/javascript/custom-components-react-x-tags.html)
## React TodoMVC Example
[TodoMVC.com](http://todomvc.com/) is a website that collects various implementations of the same basic Todo app. [Pete Hunt](http://www.petehunt.net/blog/) wrote an idiomatic React version.
> Developers these days are spoiled with choice when it comes to selecting an MV* framework for structuring and organizing their JavaScript web apps.
>
> To help solve this problem, we created TodoMVC - a project which offers the same Todo application implemented using MV* concepts in most of the popular JavaScript MV* frameworks of today.
> <figure>[![](/react/img/blog/todomvc.png)](http://todomvc.com/labs/architecture-examples/react/)</figure>
>
> [Read the source code...](https://github.com/tastejs/todomvc/tree/gh-pages/labs/architecture-examples/react)
## JSX is not HTML
Many of you pointed out differences between JSX and HTML. In order to clear up some confusion, we have added some documentation that covers the four main differences:
- [Whitespace removal](http://facebook.github.io/react/docs/jsx-is-not-html.html)
- [HTML Entities](http://facebook.github.io/react/docs/jsx-is-not-html.html)
- [Comments](http://facebook.github.io/react/docs/jsx-is-not-html.html)
- [Custom HTML Attributes](http://facebook.github.io/react/docs/jsx-is-not-html.html)

View File

@@ -0,0 +1,24 @@
---
title: "React v0.3.3"
layout: post
author: Paul O'Shannessy
---
We have a ton of great stuff coming in v0.4, but in the meantime we're releasing v0.3.3. This release addresses some small issues people were having and simplifies our tools to make them easier to use.
## react-tools
* Upgrade Commoner so `require` statements are no longer relativized when passing through the transformer. This was a feature needed when building React, but doesn't translate well for other consumers of `bin/jsx`.
* Upgraded our dependencies on Commoner and Recast so they use a different directory for their cache.
* Freeze our esprima dependency.
## React
* Allow reusing the same DOM node to render different components. e.g. `React.renderComponent(<div/>, domNode); React.renderComponent(<span/>, domNode);` will work now.
## JSXTransformer
* Improved the in-browser transformer so that transformed scripts will execute in the expected scope. The allows components to be defined and used from separate files.

View File

@@ -0,0 +1,91 @@
---
title: "Community Round-up #3"
layout: post
author: Vjeux
---
The highlight of this week is that an interaction-heavy app has been ported to React. React components are solving issues they had with nested views.
## Moving From Backbone To React
[Clay Allsopp](http://twitter.com/clayallsopp) successfuly ported [Propeller](http://usepropeller.com/blog/posts/from-backbone-to-react/), a fairly big, interaction-heavy JavaScript app, to React.
> [<img style="float: right; margin: 0 0 10px 10px;" src="/react/img/blog/propeller-logo.png" />](http://usepropeller.com/blog/posts/from-backbone-to-react/)Subviews involve a lot of easy-to-forget boilerplate that Backbone (by design) doesn't automate. Libraries like Backbone.Marionette offer more abstractions to make view nesting easier, but they're all limited by the fact that Backbone delegates how and went view-document attachment occurs to the application code.
>
> React, on the other hand, manages the DOM and only exposes real nodes at select points in its API. The "elements" you code in React are actually objects which wrap DOM nodes, not the actual objects which get inserted into the DOM. Internally, React converts those abstractions into actual DOMElements and fills out the document accordingly. [...]
>
> We moved about 20 different Backbone view classes to React over the past few weeks, including the live-preview pane that you see in our little iOS demo. Most importantly, it's allowed us to put energy into making each component work great on its own, instead of spending extra cycles to ensure they function in unison. For that reason, we think React is a more scalable way to build view-intensive apps than Backbone alone, and it doesn't require you to drop-everything-and-refactor like a move to Ember or Angular would demand.
>
> [Read the full post...](http://usepropeller.com/blog/posts/from-backbone-to-react/)
## Grunt Task for JSX
[Eric Clemmons](http://ericclemmons.github.io/) wrote a task for [Grunt](http://gruntjs.com/) that applies the JSX transformation to your Javascript files. It also works with [Browserify](http://browserify.org/) if you want all your files to be concatenated and minified together.
> Grunt task for compiling Facebook React's .jsx templates into .js
>
> ```javascript
grunt.initConfig({
react: {
app: {
options: { extension: 'js' },
files: { 'path/to/output/dir': 'path/to/jsx/templates/dir' }
```
>
> It also works great with `grunt-browserify`!
>
> ```javascript
browserify: {
options: {
transform: [ require('grunt-react').browserify ]
},
app: {
src: 'path/to/source/main.js',
dest: 'path/to/target/output.js'
```
>
> [Check out the project ...](https://github.com/ericclemmons/grunt-react)
## Backbone/Handlebars Nested Views
[Joel Burget](http://joelburget.com/) wrote a blog post talking about the way we would write React-like components in Backbone and Handlebars.
> The problem here is that we're trying to maniplate a tree, but there's a textual layer we have to go through. Our views are represented as a tree - the subviews are children of CommentCollectionView - and they end up as part of a tree in the DOM. But there's a Handlebars layer in the middle (which deals in flat strings), so the hierarchy must be destructed and rebuilt when we render.
>
> What does it take to render a collection view? In the Backbone/Handlebars view of the world you have to render the template (with stubs), render each subview which replaces a stub, and keep a reference to each subview (or anything within the view that could change in the future).
>
> So while our view is conceptually hierarchical, due to the fact that it has to go through a flat textual representation, we need to do a lot of extra work to reassemble that structure after rendering.
>
> [Read the full post...](http://joelburget.com/react/)
## JSRomandie Meetup
[Renault John Lecoultre](https://twitter.com/renajohn/) from [BugBuster](http://www.bugbuster.com) did a React introduction talk at a JS meetup called [JS Romandie](https://twitter.com/jsromandie) last week.
<script async class="speakerdeck-embed" data-id="888a9d50c01b01300df36658d0894ac1" data-ratio="1.33333333333333" src="//speakerdeck.com/assets/embed.js"></script>
## CoffeeScript integration
[Vjeux](http://blog.vjeux.com/) used the fact that JSX is just a syntactic sugar on-top of regular JS to rewrite the React front-page examples in CoffeeScript.
> Multiple people asked what's the story about JSX and CoffeeScript. There is no JSX pre-processor for CoffeeScript and I'm not aware of anyone working on it. Fortunately, CoffeeScript is pretty expressive and we can play around the syntax to come up with something that is usable.
>
> ```javascript
{div, h3, textarea} = React.DOM
(div {className: 'MarkdownEditor'}, [
(h3 {}, 'Input'),
(textarea {onKeyUp: @handleKeyUp, ref: 'textarea'},
@state.value
)
])
```
>
> [Read the full post...](http://blog.vjeux.com/2013/javascript/react-coffeescript.html)
## Tutorial in Plain Javascript
We've seen a lot of people comparing React with various frameworks. [Ricardo Tomasi](http://ricardo.cc/) decided to re-implement the tutorial without any framework, just plain Javascript.
> Facebook & Instagram launched the React framework and an accompanying tutorial. Developer Vlad Yazhbin decided to rewrite that using AngularJS. The end result is pretty neat, but if you're like me you will not actually appreciate the HTML speaking for itself and doing all the hard work. So let's see what that looks like in plain javascript.
>
> [Read the full post...](http://ricardo.cc/2013/06/07/react-tutorial-rewritten-in-plain-javascript.html)

View File

@@ -0,0 +1,52 @@
---
title: "New in React v0.4: Autobind by Default"
layout: post
author: Paul O'Shannessy
---
React v0.4 is very close to completion. As we finish it off, we'd like to share with you some of the major changes we've made since v0.3. This is the first of several posts we'll be making over the next week.
## What is React.autoBind?
If you take a look at most of our current examples, you'll see us using `React.autoBind` for event handlers. This is used in place of `Function.prototype.bind`. Remember that in JS, [function calls are late-bound](http://bonsaiden.github.io/JavaScript-Garden/#function.this). That means that if you simply pass a function around, the `this` used inside won't necessarily be the `this` you expect. `Function.prototype.bind` creates a new, properly bound, function so that when called, `this` is exactly what you expect it to be.
Before we launched React, we would write this:
```js{4}
React.createClass({
onClick: function(event) {/* do something with this */},
render: function() {
return <button onClick={this.onClick.bind(this)} />;
}
});
```
We wrote `React.autoBind` as a way to cache the function creation and save on memory usage. Since `render` can get called multiple times, if you used `this.onClick.bind(this)` you would actually create a new function on each pass. With React v0.3 you were able to write this instead:
```js{2,4}
React.createClass({
onClick: React.autoBind(function(event) {/* do something with this */}),
render: function() {
return <button onClick={this.onClick} />;
}
});
```
## What's Changing in v0.4?
After using `React.autoBind` for a few weeks, we realized that there were very few times that we didn't want that behavior. So we made it the default! Now all methods defined within `React.createClass` will already be bound to the correct instance.
Starting with v0.4 you can just write this:
```js{2,4}
React.createClass({
onClick: function(event) {/* do something with this */},
render: function() {
return <button onClick={this.onClick} />;
}
});
```
For v0.4 we will simply be making `React.autoBind` a no-op — it will just return the function you pass to it. Most likely you won't have to change your code to account for this change, though we encourage you to update. We'll publish a migration guide documenting this and other changes that come along with React v0.4.

View File

@@ -0,0 +1,58 @@
---
title: "Community Round-up #4"
layout: post
author: Vjeux
---
React reconciliation process appears to be very well suited to implement a text editor with a live preview as people at Khan Academy show us.
## Khan Academy
[Ben Kamens](http://bjk5.com/) explains how [Ben Alpert](http://benalpert.com/) and [Joel Burget](http://joelburget.com/) are promoting React inside of [Khan Academy](https://www.khanacademy.org/). They now have three projects in the works using React.
> Recently two Khan Academy devs dropped into our team chat and said they were gonna use React to write a new feature. They even hinted that we may want to adopt it product-wide.
>
> "The library is only a week old. It's a brand new way of thinking about things. We're the first to use it outside of Facebook. Heck, even the React devs were surprised to hear we're using this in production!!!"
>
> [Read the full post...](http://bjk5.com/post/53742233351/getting-your-team-to-adopt-new-technology)
The best part is the demo of how React reconciliation process makes live editing more user-friendly.
> Our renderer, post-React, is on the left. A typical math editor's preview is on the right.
> <figure>[<img src="/react/img/blog/monkeys.gif" width="70%" />](http://bjk5.com/post/53742233351/getting-your-team-to-adopt-new-technology)</figure>
## React Snippets
Over the past several weeks, members of our team, [Pete Hunt](http://www.petehunt.net/) and [Paul O'Shannessy](http://zpao.com/), answered many questions that were asked in the [React group](https://groups.google.com/forum/#!forum/reactjs). They give a good overview of how to integrate React with other libraries and APIs through the use of [Mixins](/react/docs/mixins.html) and [Lifecycle Methods](/react/docs/advanced-components.html).
> [Listening Scroll Event](https://groups.google.com/forum/#!topic/reactjs/l6PnP8qbofk)
>
> * [JSFiddle](http://jsfiddle.net/aabeL/1/): Basically I've given you two mixins. The first lets you react to global scroll events. The second is, IMO, much more useful: it gives you scroll start and scroll end events, which you can use with setState() to create components that react based on whether the user is scrolling or not.
>
> [Fade-in Transition](https://groups.google.com/forum/#!topic/reactjs/RVAY_eQmdpo)
>
> * [JSFiddle](http://jsfiddle.net/ufe8k/1/): Creating a new `<FadeInWhenAdded>` component and using jQuery `.fadeIn()` function on the DOM node.
> * [JSFiddle](http://jsfiddle.net/R8f5L/5/): Using CSS transition instead.
>
> [Socket.IO Integration](https://groups.google.com/forum/#!topic/reactjs/pyUZBRWcHB4)
>
> * [Gist](https://gist.github.com/zpao/5686416): The big thing to notice is that my component is pretty dumb (it doesn't have to be but that's how I chose to model it). All it does is render itself based on the props that are passed in. renderOrUpdate is where the "magic" happens.
> * [Gist](https://gist.github.com/petehunt/5687230): This example is doing everything -- including the IO -- inside of a single React component.
> * [Gist](https://gist.github.com/petehunt/5687276): One pattern that we use at Instagram a lot is to employ separation of concerns and consolidate I/O and state into components higher in the hierarchy to keep the rest of the components mostly stateless and purely display.
>
> [Sortable jQuery Plugin Integration](https://groups.google.com/forum/#!topic/reactjs/mHfBGI3Qwz4)
>
> * [JSFiddle](http://jsfiddle.net/LQxy7/): Your React component simply render empty divs, and then in componentDidMount() you call React.renderComponent() on each of those divs to set up a new root React tree. Be sure to explicitly unmountAndReleaseReactRootNode() for each component in componentWillUnmount().
## Introduction to React Screencast
[Pete Hunt](http://www.petehunt.net/) recorded himself implementing a simple `<Blink>` tag in React.
<figure><iframe src="http://player.vimeo.com/video/67248575" width="500" height="340" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></figure>
## Snake in React
[Tom Occhino](http://tomocchino.com/) implemented Snake in 150 lines with React.
> [Check the source on Github](https://github.com/tomocchino/react-snake/blob/master/src/snake.js)
> <figure>[![](/react/img/blog/snake.png)](http://tomocchino.github.io/react-snake/)</figure>

View File

@@ -0,0 +1,63 @@
---
title: "New in React v0.4: Prop Validation and Default Values"
layout: post
author: Paul O'Shannessy
---
Many of the questions we got following the public launch of React revolved around `props`, specifically that people wanted to do validation and to make sure their components had sensible defaults.
## Validation
Oftentimes you want to validate your `props` before you use them. Perhaps you want to ensure they are a specific type. Or maybe you want to restrict your prop to specific values. Or maybe you want to make a specific prop required. This was always possible — you could have written validations in your `render` or `componentWillReceiveProps` functions, but that gets clunky fast.
React v0.4 will provide a nice easy way for you to use built-in validators, or to even write your own.
```js
React.createClass({
propTypes: {
// An optional string prop named "description".
description: React.PropTypes.string,
// A required enum prop named "category".
category: React.PropTypes.oneOf(['News','Photos']).isRequired,
// A prop named "dialog" that requires an instance of Dialog.
dialog: React.PropTypes.instanceOf(Dialog).isRequired
},
...
});
```
## Default Values
One common pattern we've seen with our React code is to do something like this:
```js
React.createClass({
render: function() {
var value = this.props.value || 'default value';
return <div>{value}</div>;
}
});
```
Do this for a few `props` across a few components and now you have a lot of redundant code. Starting with React v0.4, you can provide default values in a declarative way:
```js
React.createClass({
getDefaultProps: function() {
return {
value: 'default value'
};
}
...
});
```
We will use the cached result of this function before each `render`. We also perform all validations before each `render` to ensure that you have all of the data you need in the right form before you try to use it.
- - -
Both of these features are entirely optional. We've found them to be increasingly valuable at Facebook as our applications grow and evolve, and we hope others find them useful as well.

View File

@@ -4,7 +4,7 @@ layout: default
sectionid: blog
---
<section class="content wrap documentationContent">
<section class="content wrap blogContent">
{% include nav_blog.html %}
<div class="inner-content">
{% for page in site.posts %}

View File

@@ -3,6 +3,7 @@ id: docs-api
title: React API
layout: docs
prev: mixins.html
next: jsx-is-not-html.html
---
## React
@@ -49,7 +50,7 @@ React.createClass({
function createClass(object specification)
```
Creates a component given a specification. A component implements a `render` method which returns a 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.
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

View File

@@ -22,7 +22,7 @@ In this one simple line, we have accomplished the following:
- The component is **mounted** into `document.body`.
**Mounting** is the process of initializing a React component by creating its
DOM nodes and inserting the them into a supplied container node.
DOM nodes and inserting them into a supplied container node.
At this point, the entire page consists of a single `<div>` with "Hello,
world!".

View File

@@ -88,6 +88,10 @@ React.renderComponent(
);
```
> 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}

View File

@@ -0,0 +1,95 @@
---
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} />
```

View File

@@ -37,7 +37,7 @@ var Nav;
// Input (JSX):
var app = <Nav color="blue" />;
// Output (JS):
var app = Nav({color:'blue'});
var app = Nav({color:'blue'}, null);
```
Notice that in order to use `<Nav />`, the `Nav` variable must be in scope.
@@ -49,11 +49,11 @@ var Nav, Profile;
// Input (JSX):
var app = <Nav color="blue"><Profile>click</Profile></Nav>;
// Output (JS):
var app = Nav({color:'blue'}, Profile({}, 'click'));
var app = Nav({color:'blue'}, Profile(null, 'click'));
```
Use the [JSX Compiler](/react/jsx-compiler.html) to try out JSX and see how it
desguars into native JavaScript.
desugars into native JavaScript.
If you want to use JSX, the [Getting Started](getting-started.html) guide shows
how to setup compilation.
@@ -114,7 +114,7 @@ var Nav;
// Input (JSX):
var tree = <Nav><span /></Nav>;
// Output (JS):
var tree = Nav({}, React.DOM.span({}));
var tree = Nav(null, React.DOM.span(null, null));
```
> Remember:
@@ -145,7 +145,7 @@ Likewise, JavaScript expressions may be used to express children:
// Input (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// Output (JS):
var content = Container({}, window.isLoggedIn ? <Nav /> : <Login />);
var content = Container(null, window.isLoggedIn ? Nav(null, null) : Login(null, null));
```
## Tooling

View File

@@ -262,8 +262,8 @@ So far we've been inserting the comments directly in the source code. Instead, l
```javascript
// tutorial8.js
var data = [
{author: 'Pete Hunt', text: 'This is one comment'},
{author: 'Jordan Walke', text: 'This is *another* comment'}
{author: "Pete Hunt", text: "This is one comment"},
{author: "Jordan Walke", text: "This is *another* comment"}
];
```
@@ -357,8 +357,8 @@ When the component is first created, we want to GET some JSON from the server an
```javascript
// tutorial13.json
[
{'author': 'Pete Hunt', 'text': 'This is one comment'},
{'author': 'Jordan Walke', 'text': 'This is *another* comment'}
{"author": "Pete Hunt", "text": "This is one comment"},
{"author": "Jordan Walke", "text": "This is *another* comment"}
]
```
@@ -435,7 +435,7 @@ React.renderComponent(
```
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 60 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
All we have done here is move the AJAX call to a separate method and call it when the component is first loaded and every 5 seconds after that. Try running this in your browser and changing the `comments.json` file; within 5 seconds, the changes will show!
## Adding new comments

View File

@@ -49,6 +49,8 @@ $ npm install -g react-tools
## Release Notes
**0.3.3** Upgrade `react-tools` dependencies, improve in-browser JSX transformer, make `React.renderComponent` more versatile. [Details...](blog/2013/06/20/react-v0-3-3.html)
**0.3.2** Improve compatibility of JSX Transformer; make `react-tools` compatible with [browserify](https://github.com/substack/node-browserify)
**0.3.1** Fix `react-tools` module

BIN
docs/img/blog/chatapp.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

BIN
docs/img/blog/monkeys.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 532 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

BIN
docs/img/blog/snake.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

BIN
docs/img/blog/todomvc.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

BIN
docs/img/blog/xreact.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

View File

@@ -56,10 +56,11 @@ id: home
<div class="example">
<h3>An Application</h3>
<p>
Using properties and state, we can put together a small Todo
application. React provides an interface to the DOM via `refs`. Although
event handlers appear to be rendered inline, they will be
collected and implemented using event delegation.
Using `props` and `state`, we can put together a small Todo application.
This example uses `state` to track the current list of items as well as
the text that the user has entered. Although event handlers appear to be
rendered inline, they will be collected and implemented using event
delegation.
</p>
<div id="todoExample"></div>
</div>

View File

@@ -13,3 +13,9 @@ id: support
## IRC
Many developers and users idle on Freenode.net's IRC network in **[#reactjs on freenode](irc://chat.freenode.net/reactjs)**.
## Twitter
[**#reactjs** hash tag on Twitter](https://twitter.com/search?q=%23reactjs) is used to keep up with the latest React news.
<center><a class="twitter-timeline" data-dnt="true" data-chrome="nofooter noheader transparent" href="https://twitter.com/search?q=%23reactjs" data-widget-id="342522405270470656"></a></center>

View File

@@ -9,6 +9,8 @@ module.exports = function() {
var args = [
"bin/jsx",
"--cache-dir", ".module-cache",
"--relativize",
config.sourceDir,
config.outputDir
];

View File

@@ -1,6 +1,6 @@
{
"name": "react-tools",
"version": "0.3.2",
"version": "0.3.3",
"keywords": [
"react",
"jsx",
@@ -36,9 +36,9 @@
},
"dependencies": {
"base62": "~0.1.1",
"commoner": "~0.6.8",
"esprima": "git://github.com/facebook/esprima#fb-harmony",
"recast": "~0.3.3",
"commoner": "~0.7.0",
"esprima": "https://github.com/facebook/esprima/tarball/ca28795124d45968e62a7b4b336d23a053ac3a84",
"recast": "~0.4.8",
"source-map": "~0.1.22"
},
"devDependencies": {

View File

@@ -106,11 +106,15 @@ var ReactMount = {
renderComponent: function(nextComponent, container) {
var prevComponent = instanceByReactRootID[getReactRootID(container)];
if (prevComponent) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps);
});
return prevComponent;
if (prevComponent.constructor === nextComponent.constructor) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps);
});
return prevComponent;
} else {
ReactMount.unmountAndReleaseReactRootNode(container);
}
}
ReactMount.prepareTopLevelEvents(ReactEventTopLevelCallback);

View File

@@ -0,0 +1,22 @@
/**
* @jsx React.DOM
* @emails react-core
*/
"use strict";
describe('ReactMount', function() {
var React = require('React');
var ReactMount = require('ReactMount');
it('should render different components in same root', function() {
var container = document.createElement('container');
document.documentElement.appendChild(container);
ReactMount.renderComponent(<div></div>, container);
expect(container.firstChild.nodeName).toBe('DIV');
ReactMount.renderComponent(<span></span>, container);
expect(container.firstChild.nodeName).toBe('SPAN');
});
});

View File

@@ -24,22 +24,22 @@ var visitors = require('./fbtransform/visitors').transformVisitors;
var transform = transform.bind(null, visitors.react);
var docblock = require('./fbtransform/lib/docblock');
var headEl = document.getElementsByTagName('head')[0];
exports.transform = transform;
exports.exec = function(code) {
return eval(transform(code));
};
var run = exports.run = function(code) {
var moduleName =
docblock.parseAsObject(docblock.extract(code)).providesModule;
var jsx =
docblock.parseAsObject(docblock.extract(code)).jsx;
window.moduleLoads = (window.moduleLoads || []).concat(moduleName);
window.startTime = Date.now();
var run = exports.run = function(code) {
var jsx = docblock.parseAsObject(docblock.extract(code)).jsx;
var functionBody = jsx ? transform(code).code : code;
Function('require', 'module', 'exports', functionBody)(require, module, exports);
window.endTime = Date.now();
require[moduleName] = module.exports;
var scriptEl = document.createElement('script');
scriptEl.innerHTML = functionBody;
headEl.appendChild(scriptEl);
};
if (typeof window === "undefined" || window === null) {
@@ -48,15 +48,17 @@ if (typeof window === "undefined" || window === null) {
var load = exports.load = function(url, callback) {
var xhr;
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP')
: new XMLHttpRequest();
// Disable async since we need to execute scripts in the order they are in the
// DOM to mirror normal script loading.
xhr.open('GET', url, false);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
var _ref;
if (xhr.readyState === 4) {
if ((_ref = xhr.status) === 0 || _ref === 200) {
if (xhr.status === 0 || xhr.status === 200) {
run(xhr.responseText);
} else {
throw new Error("Could not load " + url);
@@ -70,37 +72,19 @@ var load = exports.load = function(url, callback) {
};
runScripts = function() {
var jsxes, execute, index, length, s, scripts;
scripts = document.getElementsByTagName('script');
jsxes = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = scripts.length; _i < _len; _i++) {
s = scripts[_i];
if (s.type === 'text/jsx') {
_results.push(s);
}
}
return _results;
})();
index = 0;
length = jsxes.length;
(execute = function(j) {
var script;
script = jsxes[j];
if ((script != null ? script.type : void 0) === 'text/jsx') {
if (script.src) {
return load(script.src, execute);
} else {
run(script.innerHTML);
return execute();
}
var scripts = document.getElementsByTagName('script');
scripts = Array.prototype.slice.call(scripts);
var jsxScripts = scripts.filter(function(script) {
return script.type === 'text/jsx';
});
jsxScripts.forEach(function(script) {
if (script.src) {
load(script.src);
} else {
run(script.innerHTML);
}
});
for (var i = 0; i < jsxes.length; i++) {
execute(i);
}
return null;
};
if (window.addEventListener) {