Professional Documents
Culture Documents
Dzone RC React Essentials PDF
Dzone RC React Essentials PDF
React.js Essentials
Get More Refcardz! Visit DZone.com/Refcardz
» What Is React.js?
C O NT E NT S
» How the Magic Happens
» Component Specifications
W H AT I S R E AC T. J S? A S I M P L E “ H E L LO ” CO M P O N E N T
React (a.k.a. ReactJS or React.js) is a JavaScript library React components implement a render() method that
for creating user interfaces, open sourced to the takes input data and returns what to display.
world by Facebook and Instagram team in 2013. One
Here is an example of a simple “Hello” Component:
might think of it as the “View” in the “Model-View-
Controller” pattern. var Hello = React.createClass({
render: function () {
React’s main goal is to make development of UI return <div>Hello {this.props.name}</div>;
}
components easy and modular. It is intended to ease });
the process of building large applications using data
React.render(<Hello name="World" />, document.body);
that changes over time.
React was created by Jordan Walke, a software engineer NOTE: The XML-like syntax shown is called JSX.
at Facebook, with the influence of XHP, a PHP-based
component system that is still in use at Facebook, but Here is the same component without JSX:
also by functional programming ideas. Pete Hunt wanted
var Hello = React.createClass({displayName: "Hello",
to use React at Instagram, so he pushed to extract React render: function() {
from Facebook-specific code and open source it. return React.createElement("div", null, "Hello ", this.
props.name);
React has 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 React.render(React.createElement(Hello, {name:
"World"}), mountNode);
version with the stored virtual DOM, and using the
result to determine how to most efficiently update the
browser’s DOM. CO M P O N E N T S P E C I F I C AT I O N S
React basically batches DOM updates and then applies The displayName string is used in debugging
displayName
minimal diffs to the real DOM. messages. JSX sets this value automatically.
React.createClass({
Changes the properties and triggers a re-
setProps getInitialState: function () {
render. return { comments: [] };
},
Like setProps(), but deletes any pre-
replaceProps existing props instead of merging the two getDefaultProps: function () {
return { name: "Hello" };
objects.
}
);
LIFECYCLE METHODS Deciding when to use props and went to use state might get
NAME DESCRIPTION
tricky. The following table will help to simplify this decision:
© D Z O NE, INC . | DZ O NE .C O M
3 REACT.JS ESSENTIALS
DOM HELPERS
componentDidMount: function() {
$.ajax({
url: this.props.url,
References: Help to access the DOM nodes:
dataType: 'json', <input ref="firstName">
cache: false,
success: function(data) { this.refs.firstName
this.setState({data: data}); React.findDOMNode(this.refs.firstName).focus()
}.bind(this), React.findDOMNode(this.refs.firstName).value
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
}); DOM Events: Help to handle DOM events:
}
<input type="text"
value={this.state.value}
onChange={this.handleChange} />
S T Y L I N G YO U R CO M P O N E N TS
handleChange: function(event) {
this.setState({ value: event.target.value });
In React, styles are mentioned in line, but unlike the }
.string
.number
Primative Types .func
Most numeric values at the end of a style prop receive an
.bool
automatic “px” specification added to them (e.g., “width:
10” is read as “width: 10px”). Here is a list of properties that Reactive Elements
.element
.node
won’t get the automatic “px” suffix:
.oneOf
• boxFlex Enumerables
.oneOfType
• boxFlexGroup
.array[Of]
• columnCount .object[Of]
Arrays and Objects .instanceOf
• fillOpacity .shape
• flex
• flexGrow Sample usage:
• flexPositive
React.createClass({
• flexShrink propTypes: {
email: React.PropTypes.string,
• flexNegative firstName: React.PropTypes.string,
age: React.PropTypes.number,
• fontWeight gender: React.PropTypes.oneOf(['M','F','NA'])
node: React.PropTypes.node,
• lineClamp
cb: React.PropTypes.func.isRequired,
• lineHeight }
});
• opacity
• order Custom validation:
• orphans
propTypes: {
• strokeOpacity customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
• widows return new Error('Validation failed!');
}
• zIndex }
}
• zoom
© D Z O NE, INC . | DZ O NE .C O M
4 REACT.JS ESSENTIALS
Apart from these there are few addons that are available in
the development (unminified) version of React only: Arrow Functions
class PostInfo extends React.Component {
• TestUtils, simple helpers for writing test cases handleOptionsButtonClick = (e) => {
this.setState({showOptionsModal: true});
• Perf, for measuring performance and giving you hints on }
where to optimize. }
• react-addons-clone-with-props
• react-addons-create-fragment Destructuring & spread attributes
• react-addons-css-transition-group
class AutoloadingPostsGrid extends React.Component {
• react-addons-linked-state-mixin render() {
• react-addons-perf var {
• react-addons-pure-render-mixin className,
...others,
• react-addons-shallow-compare
// all properties of this.props except for className
• react-addons-test-utils } = this.props;
• react-addons-transition-group return <PostsGrid {...others} />
}
• react-addons-update
}
• ReactDOM.unstable_batchedUpdates in react-dom
© D Z O NE, INC . | DZ O NE .C O M
5 REACT.JS ESSENTIALS
Using props in getInitialState is an anti-pattern. Instead of: 3. Store Emits a “Change” Event.
4. View Responds to the “Change” Event
var MessageBox = React.createClass({
getInitialState: function() {
return {nameWithQualifier: 'Mr. ' + this.props.name}; Points to remember
};
render: function() { 1. A “dispatcher” is essentially an event system.
return <div>{this.state.nameWithQualifier}</div>;
} 2. There is at most one global dispatcher.
});
React.render(<MessageBox name="Rogers"/>, mountNode); 3. “Store” is specific collection of logic and data.
4. A “Store” is a singleton.
Try the following:
5. A store is not a model. A store contains models.
var MessageBox = React.createClass({
render: function() {
6. A store is the only entity in the application that is
return <div>{'Mr. ' + this.props.name}</div>; aware of how to update data.
}
}); 7. Only stores registers to dispatcher callbacks. store
React.render(<MessageBox name="Rogers"/>, mountNode);
emits an event, but not using the dispatcher!
8. When store data changes, your views shouldn’t care
NOTE: This is not an anti-pattern if we make it clear that
if things were added, deleted, or modified but just
synchronization is not the goal.
re-render.
SPREAD OPERATOR IN JSX
C H A N G E S I N R E AC T V0.1 4
var props = {};
props.foo = x; React version 0.14, released in fall of 2015, separated out all
props.bar = y;
var component = <Component {...props} />; DOM related functionality into a separate dependency, which
can be fetched from npm under the name “react-dom.”
You can also use the spread operator (...) to override props:
var props = { foo: 'default' };
Every new change in 0.14—including the major changes—is
var component = <Component {...props} foo={'override'} />; introduced with a runtime warning and will work as before
console.log(component.props.foo); // 'override'
until version 0.15 is released.
© D Z O NE, INC . | DZ O NE .C O M
6 REACT.JS ESSENTIALS
Consider a scenario where you want to test the following NOTE: For a React component, we follow the same steps along
div.js file: with it, we will have to use React.addons.TestUtils.
JOIN NOW
DZONE, INC.
150 PRESTON EXECUTIVE DR.
CARY, NC 27513
DZone communities deliver over 6 million pages each month to more than 3.3 million software
888.678.0399
developers, architects and decision makers. DZone offers something for everyone, including news, 919.678.0300
tutorials, cheat sheets, research guides, feature articles, source code and more.
REFCARDZ FEEDBACK WELCOME
"DZone is a developer's dream," says PC Magazine. refcardz@dzone.com
Copyright © 2016 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or
© D Zpermission
transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written O NE, INC |
of the. publisher.
SPONSORSHIP OPPORTUNITIES
DZ Osales@dzone.com
NE .C O M VERSION 1.0