React (a.k.a. ReactJS or React.js) is a JavaScript library for creating user interfaces, open sourced to the world by Facebook and Instagram team in 2013. One might think of it as the “View” in the “Model-View-Controller” pattern.
React’s main goal is to be simple, declarative, and compassable, as it is intended to ease the process of building large applications using data that changes over time.
React was created by Jordan Walke, a software engineer at Facebook, with the influence of XHP, a PHP-based component system that is still in use at Facebook, but also by functional programming ideas. Pete Hunt wanted to use React at Instagram, so he pushed to extract React from Facebook-specific code and open source it. (Editor's note: Some have expressed concern about the React license; see discussions here, here, and most recently (Jan2016) here, with discussion of some alternatives here. We're not lawyers but figure it's important to be aware of this sort of thing.)
React has lately gained a lot of popularity for its concept of a “virtual-DOM,” which allows it to determine which parts of the DOM have changed by diffing the new version with the stored virtual DOM, and using the result to determine how to most efficiently update the browser's DOM.
Section 2
How the Magic Happens
To get an idea of what’s going on inside React, take a look at the following diagrams demonstrating how React.js rendering and the React Virtual DOM work:
Figure 1: React.js Rendering
Figure 2: The React Virtual DOM
React basically batches DOM updates and then applies minimal diffs to the real DOM.
Section 3
A Simple "Hello" Component
React components implement a render() method that takes input data and returns what to display.
Here is a simple example of a "Hello" Component:
var Hello = React.createClass({
render: function () {
return
The render() function should be pure, meaning that it does not modify the component state. It should examine this.props and this.state and return a single child element.
getInitialState
Invoked once before the component is mounted. The return value will be used as the initial value of this.state.
getDefaultProps
Invoked once and cached when the class is created. Values in the mapping will be set on this.props.
propTypes
The propTypes object allows you to validate props being passed to your components.
mixins
The mixins array allows you to use mixins to share behavior among multiple components.
statics
The statics object allows you to define static methods that can be called on the component class.
displayName
The displayName string is used in debugging messages. JSX sets this value automatically.
Components API
setState
Merges nextState with the current state.
replaceState
Like setState(), but deletes any pre-existing state keys that are not in nextState.
forceUpdate
Call render() on the component, skipping shouldComponentUpdate()
React.findDOMNode (0.13+)
Returns the corresponding native browser DOM element.
isMounted
isMounted() returns true if the component is rendered into the DOM.
setProps
To change the properties and trigger re-render
replaceProps
Like setProps() but deletes any pre-existing props instead of merging the two objects.
Lifecycle Methods
componentWillMount
Invoked once, both on the client and server, immediately before the initial rendering occurs.
componentDidMount
Invoked on the client immediately after the initial rendering occurs.
componentWillReceiveProps
Invoked when a component is receiving new prop. Use setState() here.
shouldComponentUpdate
Invoked before rendering when new props or state are being received. Skips render() if returns false.
componentWillUpdate
Invoked immediately before rendering when new props or state are being received. Can’t use setState() here.
componentDidUpdate
Invoked immediately after the component's updates are flushed to the DOM. Operate on the DOM here.
componentWillUnmount
Invoked immediately before a component is unmounted from the DOM.
States and Properties
Props and states are both plain JS objects; a change within one of them will trigger a render. These objects are deterministic.
Deciding when to use props and went to use state might get tricky. The following table will help to simplify this decision:
Deciding factor
props
state
Can get initial value from parent Component?
Yes
Yes
Can be changed by parent Component?
Yes
No
Can set default values inside Component?
Yes
Yes
Can change inside Component?
No
Yes
Can set initial value for child Components?
Yes
Yes
Can change in child Components?
Yes
No
Section 5
AJAX Requests
React by default doesn’t provide a helper method to manage AJAX requests, but you can use any other third party JavaScript library—like jQuery or Zepto—to make necessary AJAX requests.
Below is a sample code snippet that performs an AJAX request on props.url and on success sets the data state. In case of an error, it just uses console.error to report the error.
Note: Make sure that the execution context (this) is bound to the success and error callbacks.
In React, styles are mentioned in line, but unlike the traditional way of inline CSS strings, here we specify each style as an object whose key is the camelCased version of the style name, and whose value is the style's value (usually a string).
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
React.render(
Hello World!
, mountNode);
Most numeric values at the end of a style prop receive an automatic “px” specification added to them (e.g., “width: 10” is read as “width: 10px”). Here is a list of properties that won't get the automatic "px" suffix:
boxFlex
boxFlexGroup
columnCount
fillOpacity
flex
flexGrow
flexPositive
flexShrink
flexNegative
fontWeight
lineClamp
lineHeight
opacity
order
orphans
strokeOpacity
widows
zIndex
zoom
Section 7
DOM Helpers
References
Helps to access the DOM nodes.
this.refs.firstName
React.findDOMNode(this.refs.firstName).focus()
React.findDOMNode(this.refs.firstName).value
DOM Events: Helps to handle DOM events.
handleChange: function(event) {
this.setState({ value: event.target.value });
}
class Form extends React.Component {
onChange(inputName, e) {
this.setState({
[`${inputName}Value`]: e.target.value,
});
}
}
Destructuring & spread attribute
class AutoloadingPostsGrid extends React.Component {
render() {
var {
className,
...others, // all properties of this.props except for className
} = this.props;
return
}
}
CoffeeScript and React [React v0.13.0+]
div = React.createFactory 'div'
class Counter extends React.Component
@propTypes = initialCount: React.PropTypes.number
@defaultProps = initialCount: 0
constructor: (props) ->
super props
@state = count: props.initialCount
tick: =>
@setState count: @state.count + 1
render: ->
div onClick: @tick,
'Clicks: '
@state.count
Section 8
Conventions for React DOM & JSX
React DOM elements are expected to be in camelCased.
the camelCasing of DOM matches what you would write for custom components: and
These camelCased attributes are usually what you write when updating the DOM via JS (input.maxLength).
One current confusing exception is that class= is normalized automatically into className= at transform time.
Use className attribute instead of class
Use htmlFor attribute instead of for
Use
Custom HTML attributes may be data-attr and all lower case.
Make use of ternary operators, wherever required for example: React.render(
var MessageBox = React.createClass({
render: function() {
return
{'Mr. ' + this.props.name}
;
}
});
React.render(, mountNode);
Note: It won’t be an anti-pattern if we make it clear that synchronization's not the goal.
Spread Operator in JSX:
var props = {};
props.foo = x;
props.bar = y;
var component = ;
You can also use the spread operator (...) to override props:
var props = { foo: 'default' };
var component = ;
console.log(component.props.foo); // 'override'
The spread operator is already supported for arrays in ES6. There is also an ES7 proposal for Object Rest and Spread Properties.
Section 9
The Flux Application Architecture
Flux plays a key role if your application use dynamic data.
Don't try to compare Flux to Model View Controller (MVC) architecture, Flux is just a term to describe smart uni -directional data flow.
Figure 3: An Overview of Flux Architecture
Keys ideas:
Views "Dispatch" "Actions".
"Store" Responds to Dispatched Events.
Store Emits a "Change" Event.
View Responds to the "Change" Event
Points to remember:
A "dispatcher" is essentially an event system.
There is at most one global dispatcher.
“Store” is specific collection of logic and data.
A “Store” is a singleton.
A store is not a model. A store containsmodels.
A store is the only entity in the application that is aware of how to update data.
Only stores registers to dispatcher callbacks. store emits an event, but not using the dispatcher!
When store data changes, your views shouldn't care if things were added, deleted, or modified but just re-render.
Section 10
React v0.14
React version 0.14 separated out all DOM related functionality into a separate dependency, which can be fetched from npm under the name `react-dom`
React version 0.14 separated out all DOM related functionality into a separate dependency, which can be fetched from npm under the name `react-dom`
Every new change in 0.14, including the major changes, is introduced with a runtime warning and will work as before until 0.15.
The react package contains React.createElement, .createClass, .Component, .PropTypes, .Children, and the other helpers related to elements and component classes
The react-dom package has ReactDOM.render, .unmountComponentAtNode, and .findDOMNode. In react-dom/server there is a server-side rendering support with ReactDOMServer.renderToString and .renderToStaticMarkup.
So, if you wanted to duplicate the example Hello component from earlier with react v0.14, it would look like this:
var React = require('react');
var ReactDOM = require('react-dom');
var Hello = React.createClass({
render: function() {
return
Hello World
;
}
});
ReactDOM.render(, node);
Section 11
Testing Your Application With Jest
Jest allows for painless JavaScript Unit Testing. It is built on top of the Jasmine test framework.
Consider a scenario where you want to test the following div.js file:
// sum.js
function div (value1, value2) {
return value1 / value2;
}
module.exports = sum;
1. Create a directory __tests__/ with a file div-test.js
// __tests__/sum-test.js
jest.dontMock('../sum');
describe('sum', function() {
it('divides 4 / 2 to equal 2', function() {
var sum = require('../div);
expect(div(4, 2)).toBe(2);
});
});
2. Run npm install jest-cli --save-dev
3. Add the following to your package.json
{ ... "scripts": { "test": "jest" } ... }
4. Run npm test
[PASS] __tests__/sum-test.js (0.015s)
Just follow the above steps, and you are ready to run with Jest!
Note: For a react component, we follow the same steps along with it, we will have to use ‘React.addons.TestUtils`.