One of the biggest problems with the web platform is that we've spent the last 20 years trying to shim applications into a document framework. HTML was designed to help academics share research papers, not to replace native thick-client applications, yet that's the direction it's been evolving towards.
I'm really happy to see Web Components (inc. Polymer, Angular, x-tags, and React) landing into HTML. If we accept that web apps != web pages at a spec level, hopefully we can build an awesome platform on which to create tools that leverage all the great parts of the web (linkable, available, auto-updating, device-agnostic) without the mess that we've made trying to make the web do something it wasn't designed for.
The current fad of quasi declarative web components looks like early Ext to me, and I think everyone knows how that turned out.
I really wish we took it back to a document approach. True REST, everywhere! That's new and novel. Frameworks that build in behaviors with static html - that's just a poor mans gui toolkit. I suppose the web will have go through the task of figuring out its just another in a long line of mistakes. It's like people want to rebuild xslt but badly.
I've also used Ext and FB React certainly reminds me of it. The biggest problem with ExtJS is that it wanted to be my class system, my service layer, my UI, my CSS, my everything. The APIs were convoluted. Then they switched to MVC when that was cool, but it was kind of a kludge.
Surprisingly, Angular seems to get functional modularity. Directives and filters are easily sharable, very good examples of modular components that can just be simple functions. The other part I really like in Angular is that a model is just data. Got an array? Sure, that can be a model.
I keep waiting for the point where I feel like those dirty Angular devs tricked me into using their framework, but it hasn't happened.
+1. You phrased a lot of exactly how I feel about AngularJS. I went through the React tutorial in order to compare the resulting code to AngularJS side by side. I'm holding back my thoughts until I have a chance to learn more about it, but in the mean time, a comparison of the code required to make the same app is a good start.
While SenchaTouch is definetly the best for mobile web-apps, Their framework is definetly too heavy, and becomes less and less practical espcially without their IDE. AngularJS has a better take on the problem indeed.
web apps === web pages , no matter how people try to spin it , and it will always be that way , not matter how much layers we can pile on html and javascript.
It was never intended for anything else and the fact that one has to navigate between html documents proves it.
Try to create a "webapp" without an html page -> doesnt work.
the whole web model is about documents and links.
THAT SAID
it doesnt mean one cant do awesome stuffs with it.
But sometimes developpers forget the basic of HTML when developping javascript heavy products. I myself am working on a big modeling app for CS students with angularJS ( MV* ) and jquery (+ a ton of plugin). AngularJS makes it very easy and clean.
First impression is that this is a lot like their PHP language extension XHP[1], which allows you to embed XML syntax into PHP and automatically escapes variables depending on their context (inside or outside the XML):
<?php
// note: includes omitted
if ($_POST['name']) {
echo <span>Hello, {$_POST['name']}</span>;
} else {
echo
<form method="post">
What is your name?<br />
<input type="text" name="name" />
<input type="submit" />
</form>;
}
in that snippet, the $_POST variable is correctly escaped to mitigate XSS attacks. XHP also allows you to condense complex components into a single tag.
I can see how embedding XML could be useful, but it's hard for my brain to parse. It keeps telling me some quotes missing somewhere. Maybe I'm just being anti-XML, but I don't see this getting much traction.
It would be nice to see a list of reasons one might choose this over angular or any of the other frameworks. The features and description on the homepage are pretty vague...
Apparently, you don't use this instead of another framework, but with (http://facebook.github.io/react/docs/common-questions.html).
To me, the closest existing thing to this would be Coffeescript as both need to be compiled into plain Javascript.
Okay, so I can use it with other libraries. But they haven't told me why I would. What problems, eg, is it solving that angular is not, or in a better way than angular does?
React 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 fulfills the role of the view (and maybe the controller, depending on your definition).
React's technique is to break your view down into smaller, composable components. These components provide a render() method which specifies how the component will generate its markup. render() can either return normal DOM elements (like <div>s) or can return other components.
When your data changes, the render() method is called again. We compare the old render()'d version with the new one and the framework determines the most efficient way to update the DOM. Often this will be faster than hand-coding it, as React knows about the entire state of the page and can do cool tricks like batching reads and writes.
The way we're able to pull this off is by constructing a very fast, lightweight representation of the DOM which knows which parts are dirtied and which parts are clean.
Because this rerender is so fast (on the order of 1ms for TodoMVC), we don't need the end user to explicitly specify data bindings. We've found that this is an easy way to build apps.
Wow, OK. This could definitely do with being included in the introduction - my first impression was "calling render() all the time and rebuilding the chunk of HTML must result in terrible performance on mobile devices etc". Your explanation here makes the whole system make a ton more sense.
Thanks for answering. It's nice to know the technical details, and I feel like you partially answered my question, but I'm still not 100% clear on the advantages over angular. What I gathered from your answer is that 2 advantages are:
1. It's faster than angular. Perhaps able to handle larger applications with tons of things going on better? But how large is large? I want to see an example app that React handles easily and angular struggles with. I know the Todo App example is mandatory, but angular (and every other framework) handles those well already.
2. It's perhaps easier to code and maintain than angular. I'm guessing this from your comment about data-bindings being unnecessary. But I'm not totally clear, as data-binding and updates are automatic in angular.
I know there are politics involved when comparing yourself to a competitor, and most programmers seem to be overly respectful of their peers, which I can appreciate. But it's too easy to fall back on the party lines "X and Y solve different problems", "X and Y have different strengths", and "You should try both out and decide for yourself!" As a framework user, these kinds of niceties are unhelpful and frustrating. It shouldn't be considered rude or disrespectful to factually list the advantages of your framework over the obvious alternatives. It is, after all, the only thing I'm really interested in as a user.
So my suggestions would be:
A bullet point list of advantages of this framework over angular, being as clear and specific as possible.
If they're good for different situations, I want to know what those situations are.
A big showcase app with the tons of components you alluded to, all working in beautiful harmony. I should be able to click a link to see the demo, not have to pull from github. And ideally there would be some accompanying walkthrough showing code snippets for various parts of the app, and explaining why they are so awesome.
React's technique is to break your view down into smaller, composable components. These components provide a render() method which specifies how the component will generate its markup. render() can either return normal DOM elements (like <div>s) or can return other components.
When your data changes, the render() method is called again. We compare the old render()'d version with the new one and the framework determines the most efficient way to update the DOM. Often this will be faster than hand-coding it, as React knows about the entire state of the page and can do cool tricks like batching reads and writes.
The way we're able to pull this off is by constructing a very fast, lightweight representation of the DOM which knows which parts are dirtied and which parts are clean.
This describes angular, that's what angular does. Edit: Well it's similar to what angular does, the intent is the same, but it doesn't know the state of the DOM among other things.
Because this rerender is so fast (on the order of 1ms for TodoMVC), we don't need the end user to explicitly specify data bindings. We've found that this is an easy way to build apps.
Angular's got a lot of great ideas, but the key difference is how you build with React.
Angular's directives are pretty similar conceptually to React components, yes. But Angular requires you to imperatively manipulate the DOM in its linking functions, whereas with React you declaratively specify how you want your component to look and when it changes state the framework computes the fastest DOM manipulations for you, which we think saves you some work and is often more performant.
If I had thorough benchmarks available I'd provide them, but sadly benchmarking things correctly is a lot of work and I just don't have time :/ You could try to play around with both frameworks' TodoMVC examples with Chrome's devtools to compare them, though.
Angular douesn't require you to use linking functions. They aren't necessary for 90% of the time when you can just use a template and a controller. It would be interesting if you provided an example in React of something that did require a linking function in Angular.
I wish we had some bigger examples checked into the repo. I'll work on fixing that. A few things:
- We've built lots of big components on Facebook and all of Instagram.com with it. Those are pretty big apps (though I know, you're asking for code and want proof).
- I think that composing UIs with JavaScript and components is easier than using directives or a templating language. For example, because Angular uses ng-repeat to construct lists, if you want alternating row colors you use something like ng-class-even. I think that creating a new directive for every use case is less intuitive than how you'd do it in React:
We could be more flexible than that. Let's say we wanted to, for some reason capitalize every other row. With Angular we'd need to create a new directive, with React it's just:
If is as fast as described, it's a godsend to Backbone developers. I love Backbone, but as I described below, I've ended up learning AngularJS because handling the DOM can be so tricky and cumbersome when you use Backbone.
And AngularJS is a great project that definitely solves most performance issues, but as you pointed out, many facets of directives are pretty unintuitive. And integrating third-party libraries is a pain with AngularJS.
So I'm really excited about trying this out. I really like the sample you put on pastebin -- very intuitive for Backbone devs.
thanks for the examples. it actually seems analogous to angular. the "createClass" bit is like a directive definition, and the "renderComponent" bit is like your new declarative markup. i do agree that angular can be complex and opaque, especially once you start to delve into the internals (compiling, priority, transclusion, etc), and avoiding that complexity is a good selling point. if i were you, i would hit that hard :)
that said, those examples don't seem all that different to me than the angular way. maybe the simplicity would start to shine in more complex use cases. again, a good toy problem that requires angular gymnastics to solve, side by side with a straightforward react version would be compelling.
my final and important question is this: you mentioned react only solves the view problem. does that mean if i want to migrate from angular to react that i would have move from angular to "react + backbone" or "react + something else"?
For Instagram we have higher level components that do data fetching via a JSON GET request. When the request comes back we store the response in state, and then we pass that state down to child components. We also pass callbacks down to those child components, so that when they want to perform a write to the server, the higher level component can do that.
We move the actual server request and response logic out of the component, of course, so it's just a one-liner within that component.
Instagram got really far with that, but there are parts of Instagram (converted from an earlier Backbone version) that have the child components directly update Backbone models which then handle the server requests. The on change Backbone events then trigger setState() calls on our UI.
At Facebook we have an in-house dataflow architecture that updates our components.
So it really depends on how you want to do it. But we don't provide a "React.Data" or "React.Router" or anything like that. This is by design, since we can't possibly account for everyone's specific use case.
I like the idea of being able to use my own raw domain objects as the model, which in angular you are supposed to wrap up as a service as i understand it -- a bit of boilerplate i don't love. I'll definitely keep my eye on this project, it sounds like it has a nice architecture.
My last piece of advice is docs, docs, docs. Making a framework easy to learn by example is the key to adoption imo. That was one of the chief complaints you heard about ember, though I think they've started to fix that. It's boring work and hard to make good docs, but it's so so important.
> I like the idea of being able to use my own raw domain objects as the model, which in angular you are supposed to wrap up as a service as i understand it -- a bit of boilerplate i don't love.
This is only a cultural thing. Angular is, at its root, a dependency injection framework. The upside of doing thinngs the angular way is that you can wire things together differently down the line (and you can actually get a lot of code reuse if you write 1-2 function services) with the downside being the boilerplate wrappers.
Thanks for taking the time to follow this conversation through :) We've spent a lot of time getting the docs to where they are today, but there's always more to do. We have more planned but think we got a pretty good point for our initial public release.
When we've showed the site internally at FB & Instagram we got a lot of the same feedback you're giving now, that we need more examples. We have some more in the repo and more we'd like to write. Coming soon!
Some things after I've been working with it for a few months
1) One of the great thing of React to me is the fact that we're writing everything in Javascript. With a very small syntax enhancer that is JSX you can write XML inside of the Javascript.
The end result is that you don't need to learn a template language or many new concepts such as all the ng-repeat, or code inside of strings that angular has.
If the framework doesn't support something, you can just implement it yourself. The React dom nodes are just regular javascript objects and you use regular arrays to manipulate them.
It is also very convenient to be able to write XML in Javascript. You work with html trees all the time yet you can't easily make new ones in js.
2) Having a representation of the DOM in javascript is a huge enabler.
Out of the box we can batch all the expensive DOM operations and only update the parts that actually changed.
But it allows to do more crazy things. We can put all our application logic in a web worker or render the page server side. There are a lot of cool possibilities once you are in a React world.
3) One of the huge issue we face as js developer is traversing the dom to get a reference to whatever node we want. jQuery shine with that. React transforms the paradigm. Instead of finding dom nodes you are creating them.
It leads to different ways of seeing the world. If you want to hide an element, instead of finding it and hiding it, you just don't create it in the first place.
This is great. To be frank, if I knew this was in the pipeline, I wouldn't have spent the past few months learning AngularJS. AngularJS, but it's fairly unintuitive to learn, and working with 3rd party libraries can be a pain with AngularJS. Most importantly, I already had a good grasp of Backbone. I love how Backbone organizes apps, and I love consuming REST APIs with Backbone. But handling the DOM is a pain in Backbone, and can result in performance issues if you're not careful.
This project appears to solve this issue and to integrate well with Backbone. I'm really looking forward to learning more about React.js.
Curious about this one (coming from mobile web perspective crappy cpu, high latency).
Render the page with node / serve html / React calls its render functions? / something else ? How does it bind to the already existing dom without building it? do all the render()s have to be called twice (once on server, once on client)?
Hey, I built this feature and was super stoked about it :)
First of all, we haven't released the official server rendering stuff yet, since the API still needs to be cleaned up. But it's a total of 20 lines or so, so I'll likely post an example soon :)
So React has a very low degree of coupling to the browser. Specifically it has two phases:
1. Generate the HTML markup, giving each DOM node a unique ID
2. Attach top-level event handlers. When an event fires we look at the target ID to figure out which component to bubble to (we have normalized, cross-browser bubbling and capturing built into our synthetic event system).
In client-rendered apps we run both of these on the client. For server rendered apps, we initialize and only generate markup on the server and send it down. Then on the client we re-initialize, but notice that the markup is there so we just attach event handlers.
This system enabled us to build a prototype a while back that ran React entirely in a web worker, but we haven't had time to productionize that yet.
Consider the architectural difference of React vs. one of the similar "view model" frameworks. It's similar to the difference between Git vs. SVN.
Other view model frameworks typically track all changes to the view model by explicitly firing an event for every delta change. That in turn causes another delta and so on. This is similar to SVN where every change is a delta from the previous state. That means that you'll need to codify every possible diff through your view hierarchy/graph. For simple stuff, they have built-in tools to help you do this. For complex views, that's really difficult or impossible (you can get into conflicts and deadlocks).
React makes it easy by simply regenerating a copy of the next view. This is similar to Git where every change is a snapshot.
There are benefits with either architecture, but I'd recommend you figure out what benefits matter more for your use case. I'm just pointing out one area where React is different.
Yeah, I'm not sure how I feel about that. Something like Ploymer[1], where you define the new tags (and their templates) separately from the JavaScript code that powers them, makes a bit more sense to me.
"Pre-process" isn't quite accurate. To me that implies processing before serving, but it appears JSX is processed in the browser by a transpiler weighing in at 300k (uncompressed). http://fb.me/JSXTransformer-0.3.0.js
Thanks for the FYI. I'd consider swapping the order and list the offline method first, since that's the more common approach people take (I'd hope), and it's easier to grok at a glance.
You can also process it offline, so you only ship standard JS. The in-browser processing is an option you can choose to use at development time if you find it quicker/simpler.
Presumably if you run the pre-processer as part of your deploy (the jsx node.js command-line tool) you don't have to ship the pre-processing library to the client.
You can do `<script type="anything-you-want"></script>`. It's just an attribute. The browser will not run any code in the tag because the `type`-attribute
is invalid now.
The next step is to create a compiler for your `anything-you-want` language. That means it transforms the textual contents of the script tag into a
string of javascript, and then calls `eval` on the string.
> This breaks code editors, static analysis tools like jshint etc.
You're right. One of our goals in the coming months is to try to make some language files for editors. Vim actually does a pretty good job of this already thanks to the similarity to E4X.
JSHint is another thing we'd like to improve upon. At Facebook & Instagram, we actually lint against the transformed code. Right now the transforms don't modify line numbers so it's been easy to match up. We'd like to build some tooling around this for people who make use of React and JSX.
> I think Web Components is landing soon, and this seems like it could leverage that.
I like the way you think! We've started thinking about that already.
Any chance of having CoffeeScript integration? Instead of inlining straight XML, can we wrap it in a function call (like gettext style) so it does not break existing languages/editors?
When you need this, you need it. When you don't, prefer static html.
Keep in mind, the folks who write developer documentation for things like this have had their head in this problem space for a long time. So there's less explanation of the "what" and "why", and examples tend to be more oriented to the "how".
Right, I said "static html" not meaning to imply that it was the same thing. I wouldn't consider "straight html" to include script code, but I think it's a valid criticism of my advice that it is oversimplistic.
Got me really excited but I found that the "why" was missing. Not sure why I would start using it. And I feel like the examples don't explain it very well.. As someone else pointed out, it feels like it's very hard to do simple stuff (from the examples!). I'm sure the landing page will get better at explaining it! For now, maybe adding it to the FAQ could be a quick way to solve this issue (I looked there).
I'm happy to see they open-sourced it. I always was wondering how the framework could look like that produces code like on the instagram.com webapp and Facebook. Especially since instagram.com is still pretty new and would not suffer from legacy decisions like parts of Facebook may still do.
React gives you a set of tools to generate markup safely. The syntax we prefer to use for it is JSX, but if you'd prefer to do it your own way, that's great too. You can organize your app however you want by splitting the DOM generation code into separate files if you wish.
Could you elaborate on that? I've seen that viewpoint a number of times but I've never understood why it's considered a cardinal sin to have templates generated from js.
I'm very confused as to what this is and how you'd go about "building user interfaces" using this. Is it an Ember/Angular competitor? Does it replace or complement a back-end stack?
React is not a standard MVC framework -- we simply strive to be a fast and easy-to-use way to build UI components. You can integrate with any backend (or frontend!) stack that you want.
The reason you'd probably want to use React is that there aren't a lot of concepts to learn, it's fast out of the box, and it ensures that your UI stays consistent with your data without manually specifying data bindings or anything like that.
FYI, I've built a transform[1] for browserify for JSX — now React apps can be written with JSX and using CommonJS module system and then consumed by browsers.
P.S. It doesn't work now with react-tools installed from npm due to bug with their release, which is now fixed in the repo but isn't released yet.
So can this do desktop-like interfaces? We've got a plethora of frameworks now, but sadly none of the offers a good option for more "dense" apps. It's all good and well if I "just" want to do a highly interactive web page, up to a gmail level, but if I want a Swing/Cocoa/Windows-like experience, it's either ext or native...
This looks really nice, will be spending some time with it. Seems like it could benefit a lot from a rich component library -- is there anything like that on the web somewhere or in the works?
I think it would help if you laid out why you're better/worse than some of the libraries already out there? That would make a great section on your site, and would set you apart
Well (i could go on all day), I wish that these libraries would start with the "big picture", as in how everything should hang together and where there component fits in, like what John Papa has done really well : http://www.johnpapa.net/spa/
It seems here we just dive straight into the code.
In particular, I don't like so much coupling of the code and the html together, but that really depends what angle you are coming from, who is the target market of this library.
For example : Take KnockoutJS, it has really good separation of concerns. I really like the MVVM pattern, why? because it means if I have a team of HTML5/CSS design guys, I can let them work off just building good markup and focus on delivering quality static stuff, then my UI developers can work on custom binding handlers for nice CSS3 transition integration and then by C#/Java guys can get their paws wet implementing the data/server functionality without ever treading on each others toes.
I thorughly agree that functional programming concepts are very healthy for a program. Great functional Composability makes reusability and maintainability a dream.
Agreed, with people at twitter, facebook and all other places constantly coming up with more and more JS libraries, there is enough evidence that the existing ones are insufficient at some level. And even if they weren't, having choices is good to have in an open source (very loosely used) community.
I'm admittedly biased (as someone who doesn't care much for JavaScript) but I take the flailing framework situation as confirmation that JavaScript+DOM is a shitty foundation to build full-fledged apps in.
Arguably, this problem happened to Java web frameworks.
Too few and you lack innovation and fresh ideas, and things get driven to ideological extremes that aren't healthy or suitable for everyone (I don't want to start a flame war, but I feel a bit that way about Rails).
Too many and none of them get enough community or support to reach critical mass. What this meant for Java is that most people ended up being forced to use J2EE frameworks designed by committee which were awful, and drove a lot of people away from Java altogether.
Actually what I've seen with Java is that the committee-designed J2EE frameworks failed to keep up and got left behind. In the last five years, the only times I've heard of teams using EJB or JSF were either moving away from them or embarrassed by them.
More number of js frameworks there are for serving similar needs, more fragmentation there will be. Fragmentation leads to in stagnation in development process (slower bug fixes and feature delivery) and broken community support that can't gain critical mass.
Ruby community somehow avoided this fate, and almost everyone pushed for Ruby on Rails as the single dominant web framework of choice for Ruby. Sure there's Sinatra, but it's miniscule compared to Ruby.
> Ruby community somehow avoided this fate, and almost everyone pushed for Ruby on Rails as the single dominant web framework of choice for Ruby.
Well, that's not really true. There was considerable pushback against RoR as a web framework, leading to lots of alternatives, most notably Merb, and to Rack as an underlying platform for web frameworks.
Eventually, though, Merb and Rails merged, Rails incorporated Rack, and Rails incorporated a mechanism for running other Rack applications as endpoints alongside traditional Rails endpoints. Furthermore, while Rails is the dominant full-stack framework (largely, through having directly incorporated much of the competition into Rails), there's plenty of alternatives for many of Rails core components (e.g., lots of alternative ORMs to ActiveRecord.)
Mixing js and xml syntax, variables in docblocks, DOM components that are not really DOM components ("React.DOM components look like browser DOM elements, they differ in a few ways"), undocumented/obscure OO features (React.createClass?). Yikes. Thank you, but no, thank you.
I'm really happy to see Web Components (inc. Polymer, Angular, x-tags, and React) landing into HTML. If we accept that web apps != web pages at a spec level, hopefully we can build an awesome platform on which to create tools that leverage all the great parts of the web (linkable, available, auto-updating, device-agnostic) without the mess that we've made trying to make the web do something it wasn't designed for.