Facebook's React vs AngularJS: A Closer Look
When we launched React | A JavaScript library for building user interfaces two weeks ago there were a few comparisons to AngularJS (Facebook’s New React JavaScript Library Tutorial Rewritten in AngularJS). We already talked about how React works and its philosophy (React | Why did we build React?), but let's get a little more concrete and look at React and Angular code side-by-side.
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.
All of the code in this post is on GitHub at https://github.com/petehunt/angu....
The app
The tutorial creates an "n star" rating widget. Here's what the widget looks like:

You can play with it here: http://jsfiddle.net/abhiroop/G3U...
The HTML page
First let's look at Angular's HTML:
- <!DOCTYPE html>
- <html ng-app="FundooDirectiveTutorial">
- <head>
- <title>Rating Directive Demo</title>
- <link rel="stylesheet" href="rating.css"/>
- </head>
- <body ng-controller="FundooCtrl">
- Rating is {{rating}} <br/>
- Clickable Rating <br/>
- <div fundoo-rating rating-value="rating" max="10" on-rating-selected="saveRatingToServer(rating)"></div>
- <br/>
- Readonly rating <br/>
- <div fundoo-rating rating-value="rating" max="10" readonly="true"></div>
- <script type="text/javascript" src="Page on Googleapis"></script>
- <script type="text/javascript" src="rating.js"></script>
- </body>
- </html>
It's a pretty straightforward document, except it includes magical HTML attributes. With React you simply mount a component into a plain HTML page via JavaScript. Here's what it looks like:
- <!DOCTYPE html>
- <html>
- <head>
- <title>Rating Directive Demo</title>
- <link rel="stylesheet" href="rating.css"/>
- <script type="text/javascript" src="http://dragon.ak.fbcdn.net/hphotos-ak-ash3/851560_459383004151757_22266_n.js"></script>
- <script type="text/javascript" src="http://dragon.ak.fbcdn.net/hphotos-ak-prn1/851582_580035725361422_42012_n.js"></script>
- <script type="text/jsx" src="rating.js"></script>
- </head>
- <body>
- </body>
- </html>
Nothing interesting here (except we're using an in-browser transformer for development; see React | Getting Started for more info). Some JavaScript will mount our component in document.body.
The CSS is shared between the Angular and React versions so I've omitted it.
The JavaScript
Let's look at Angular's JavaScript. It defines a module, a controller and a directive:
- angular.module('FundooDirectiveTutorial', [])
- .controller('FundooCtrl', function($scope, $window) {
- $scope.rating = 5;
- $scope.saveRatingToServer = function(rating) {
- $window.alert('Rating selected - ' + rating);
- };
- })
- .directive('fundooRating', function () {
- return {
- restrict: 'A',
- template: '<ul class="rating">' +
- '<li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)">' +
- '\u2605' +
- '</li>' +
- '</ul>',
- scope: {
- ratingValue: '=',
- max: '=',
- readonly: '@',
- onRatingSelected: '&'
- },
- link: function (scope, elem, attrs) {
- var updateStars = function() {
- scope.stars = [];
- for (var i = 0; i < scope.max; i++) {
- scope.stars.push({filled: i < scope.ratingValue});
- }
- };
- scope.toggle = function(index) {
- if (scope.readonly && scope.readonly === 'true') {
- return;
- }
- scope.ratingValue = index + 1;
- scope.onRatingSelected({rating: index + 1});
- };
- scope.$watch('ratingValue', function(oldVal, newVal) {
- if (newVal) {
- updateStars();
- }
- });
- }
- }
- });
Notice the HTML template defined in a string. The provided linking function tells Angular how to imperatively update the DOM when the rating changes via an explicit callback. There is also a scope which is similar to, but behaves differently than, a JavaScript environment.
Let's look at the React version.
- /** @jsx React.DOM */
- var FundooRating = React.createClass({
- render: function() {
- var items = [];
- for (var i = 1; i <= this.props.max; i++) {
- var clickHandler = this.props.onRatingSelected && this.props.onRatingSelected.bind(null, i);
- items.push(<li class={i <= this.props.value && 'filled'} onClick={clickHandler}>{'\u2605'}</li>);
- }
- return <ul class="rating">{items}</ul>;
- }
- });
- var FundooDirectiveTutorial = React.createClass({
- getInitialState: function() {
- return {rating: 5};
- },
- handleRatingSelected: React.autoBind(function(rating) {
- this.setState({rating: rating});
- alert('Rating selected - ' + rating);
- }),
- render: function() {
- return (
- <div>
- Rating is {this.state.rating}<br/>
- Clickable Rating <br/>
- <FundooRating value={this.state.rating} max="10" onRatingSelected={this.handleRatingSelected} />
- <br />
- Readonly rating <br/>
- <FundooRating value={this.state.rating} max="10" />
- </div>
- );
- }
- });
- React.renderComponent(<FundooDirectiveTutorial />, document.body);
The markup syntax you see is JSX and we've discussed it at length in React | JSX Syntax. We prefer it, but it's not required to use React.
React doesn't have templates since we use JavaScript to generate the markup (via JSX or function calls).
There's no linking function because React figures out how to most efficiently update the DOM for you when your data changes. Just write your render() function and React will keep the UI up-to-date for you.
There are no scopes or other nonstandard concepts besides components (which are just objects) since you're just using plain, familiar JavaScript to express your display logic.
We have plenty of documentation starting with React | Tutorial to explain how all of this works. The important takeaway is that you provide a render() method that declaratively specifies how you want your UI to look. When the data changes, React calls your render() method again, diffs the old return value with the new one and figures out how to update the DOM for you.
React vs AngularJS by the (highly unscientific) numbers
Number of concepts to learn
- React: 2 (everything is a component, some components have state). As your app grows, there's nothing more to learn; just build more modular components.
- AngularJS: 6 (modules, controllers, directives, scopes, templates, linking functions). As your app grows, you'll need to learn more concepts.
Lines of code
- React: 47 (12 HTML, 35 JS)
- AngularJS: 64 (18 HTML, 46 JS)
Comparing technology is hard.
It's hard to compare two technologies in an objective way in a single blog post. I'm sure it's possible to code golf the Angular example to be smaller than React, so certainly don't take these numbers too seriously.
Using React and AngularJS together
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.
First, let's bring back the original AngularJS HTML page and add the React dependencies:
- <!DOCTYPE html>
- <html ng-app="FundooDirectiveTutorial">
- <head>
- <title>Rating Directive Demo</title>
- <link rel="stylesheet" href="rating.css"/>
- </head>
- <body ng-controller="FundooCtrl">
- Rating is {{rating}} <br/>
- Clickable Rating <br/>
- <div fundoo-rating rating-value="rating" max="10" on-rating-selected="saveRatingToServer(rating)"></div>
- <br/>
- Readonly rating <br/>
- <div fundoo-rating rating-value="rating" max="10" readonly="true"></div>
- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
- <script type="text/javascript" src="http://dragon.ak.fbcdn.net/hphotos-ak-ash3/851560_459383004151757_22266_n.js"></script>
- <script type="text/javascript" src="rating-react.build.js"></script>
- <script type="text/javascript" src="rating-angular.js"></script>
- </body>
- </html>
Note: for this example we're precompiling a rating-react.js file using JSX syntax to rating-react.build.js using react-tools.
Next let's strip down the React version to the bare minimum we need to support the directive:
- /** @jsx React.DOM */
- window.FundooRating = React.createClass({
- render: function() {
- var items = [];
- for (var i = 0; i < this.props.scope.max; i++) {
- var clickHandler = this.props.scope.$apply.bind(this.props.scope, this.props.scope.toggle.bind(null, i));
- items.push(<li class={i < this.props.scope.ratingValue && 'filled'} onClick={clickHandler}>{'\u2605'}</li>);
- }
- return <ul class="rating">{items}</ul>;
- }
- });
And finally, here's what remains of the Angular JavaScript code:
- angular.module('FundooDirectiveTutorial', [])
- .controller('FundooCtrl', function($scope, $window) {
- $scope.rating = 5;
- $scope.saveRatingToServer = function(rating) {
- $window.alert('Rating selected - ' + rating);
- };
- })
- .directive('fundooRating', function () {
- return {
- restrict: 'A',
- scope: {
- ratingValue: '=',
- max: '=',
- readonly: '@',
- onRatingSelected: '&'
- },
- link: function (scope, elem, attrs) {
- scope.toggle = function(index) {
- if (scope.readonly && scope.readonly === 'true') {
- return;
- }
- scope.ratingValue = index + 1;
- scope.onRatingSelected({rating: index + 1});
- };
- scope.$watch('ratingValue', function(oldVal, newVal) {
- React.renderComponent(window.FundooRating({scope: scope}), elem[0]);
- });
- }
- }
- });
We've changed the watch expression to simply call React.renderComponent() whenever the data changes. React is smart enough to do this efficiently. You don't have to write any code to update your UI.
This version clocks in at 62 loc, which is between the pure-React and pure-Angular version.
The conclusion
AngularJS is a great tool for building web apps.
If you like Angular, we think you'll love React because reactive updates are so easy and composable components are a simple and powerful abstraction for large and small applications.
Head on over to React | A JavaScript library for building user interfaces
write by Pete Hunt
Facebook's React vs AngularJS: A Closer Look的更多相关文章
- Facebook的React Native之所以能打败谷歌的原因有7个(ReactNative vs Flutter)
		https://baijiahao.baidu.com/s?id=1611028483072699113&wfr=spider&for=pc 如果你喜欢用(或希望能够用)模板搭建应用, ... 
- 关于 Facebook 的 React 专利许可证
		本文转载自:酷 壳 – CoolShell 作者:陈皓 随着 Apache.百度.Wordpress 都在和 Facebook 的 React.js 以及其专利许可证划清界限,似乎大家又在讨论 Fac ... 
- 移动应用跨平台框架江湖将现终结者?速来参拜来自Facebook的React Native
		React Native使用初探 February 06 2015 Facebook让所有React Conf的参与人员都可以初尝React Native的源码---一个编写原生移动应用的方法.该方法 ... 
- Facebook发布React 16 专利条款改为MIT开源协议
		9 月 26 日,用于构建 UI 的 JavaScript 库 React 16 的最新版本上线. Facebook 最终在现有的两种 React 版本中选择了出现 bug 概率最少的一款.这次版本更 ... 
- ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app
		转载:http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-a ... 
- Facebook的Web开发三板斧:React.js、Relay和GraphQL
		2015-02-26 孙镜涛 InfoQ Eric Florenzano最近在自己的博客上发表了一篇题为<Facebook教我们如何构建网站>的文章,他认为软件开发有些时候需要比较大的跨 ... 
- 【转】Facebook React 和 Web Components(Polymer)对比优势和劣势
		原文转自:http://segmentfault.com/blog/nightire/1190000000753400 译者前言 这是一篇来自 StackOverflow 的问答,提问的人认为 Rea ... 
- [React] React Fundamentals: Integrating Components with D3 and AngularJS
		Since React is only interested in the V (view) of MVC, it plays well with other toolkits and framewo ... 
- Facebook React 和 Web Components(Polymer)对比优势和劣势
		目录结构 译者前言 Native vs. Compiled 原生语言对决预编译语言 Internal vs. External DSLs 内部与外部 DSLs 的对决 Types of DSLs - ... 
随机推荐
- Vue项目启动后首页URL带的#该怎么去掉?
			修改router的mode为history就可以 const router = new VueRouter({mode: 'history', routes: [...]}) 实际修改后需要注意修改a ... 
- 深入浅出 JavaScript 关键词 -- this
			深入浅出 JavaScript 关键词 -- this 要说 JavaScript 这门语言最容易让人困惑的知识点,this 关键词肯定算一个.JavaScript 语言面世多年,一直在进化完善,现在 ... 
- CF126B
			CF126B Password 题意: 给出一个字符串 H,找一个最长的字符串 h,使得它既作为前缀出现过.又作为后缀出现过.还作为中间的子串出现过. 解法: 沿着 $ next_n $ 枚举字符串, ... 
- 造轮子和用轮子:快速入门JavaScript模块化
			造轮子和用轮子:快速入门JavaScript模块化 前言 都说“不重复造轮子”,就像iPhone——它除了打电话还可以播放音乐——但是工程师不用从零开始做一个音乐播放功能,也许只要在iPhone的系统 ... 
- linux之nginx
			一.知识点回顾 临时:关闭当前正在运行的 /etc/init.d/iptables stop 永久:关闭开机自启动 chkonfig iptables off ll /var/log/secure # ... 
- C++ code:向量操作之添加元素
			读入一个文件aaa.txt的数据到向量中,文件中是一些整数(个数未知).要判断向量中的元素有多少个两两相等的数对. 代码如下: #include<iostream> #include< ... 
- bzoj营业额统计
			这个也是板子题吧,很水,求前驱后继即可 /* 插入,求前驱和后继 */ #include<iostream> #include<cstring> #include<cst ... 
- 【AtCoder】ARC081
			C - Make a Rectangle 每次取两个相同的且最大的边,取两次即可 #include <bits/stdc++.h> #define fi first #define se ... 
- 在python3下使用requests,xpath,urllib爬取不得姐网站相关视频爬虫源代码
			#coding=utf-8 from lxml import etreeimport requestsimport urllibimport os # 获取url的html等内容def getHtml ... 
- 陈国凯oi历程
			从此成了OI退役狗 说实话,当时NOIP比赛前就想写这篇,结果一直没有足够的动力和时间写,现在高考完了,也有了时间,就写一点东西,记录一下我的OI经历吧. 初入OI 高一时,我是信息技术课代表(当然没 ... 
