React - Js Essentials
React - Js Essentials
224
What Is React.js?
How the Magic Happens
A Simple Hello Component
Component Specifications
React.js Essentials
By Hemanth H.M.
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 components implement a render() method that
takes input data and returns what to display.
React.render(React.createElement(Hello, {name:
"World"}), mountNode);
CO M P O N E N T S P E C I F I C AT I O N S
NAME
DESCRIPTION
render
child element.
REJAVA
ACT.JSENTERPRISE
ESSENTIALS EDITION 7
getDefaultProps
propTypes
mixins
statics
D Z O NE, INC.
displayName
DZ O NE.C O M
2
COMPONENTS API
NAME
setState
DESCRIPTION
Props and states are both plain JS objects; a change within one
of them will trigger a render. These objects are deterministic.
replaceState
// state
this.setState({ user: 'hemanth' });
this.replaceState({ ... });
this.state.username //=> 'hemanth'
render: function () {
return <div className={this.props.fullscreen ? 'full' :
''}>
Hello, {this.state.username}
</div>;
}
nextState.
forceUpdate
React.findDOMNode
(0.13+)
isMounted
setProps
React.createClass({
getInitialState: function () {
return { comments: [] };
},
replaceProps
REACT.JS ESSENTIALS
getDefaultProps: function () {
return { name: "Hello" };
}
);
LIFECYCLE METHODS
NAME
Deciding when to use props and went to use state might get
DESCRIPTION
componentWillMount
componentDidMount
PROPS
STATE
Yes
Yes
Yes
No
Yes
Yes
No
Yes
Yes
Yes
Yes
No
componentWillReceiveProps
DECIDING FACTOR
shouldComponentUpdate
componentWillUpdate
componentDidUpdate
componentWillUnmount
A J A X R E Q U E S TS
React by default doesnt provide a helper method to manage
AJAX requests, but you can use any other third party
JavaScript librarylike jQuery or Zeptoto 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
DZ O NE .C O M
REACT.JS ESSENTIALS
DOM HELPERS
componentDidMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
}
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 });
}
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')',
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all'
// 'ms' is the only lowercase vendor prefix
};
React.createClass({
mixins: [React.addons.LinkedStateMixin]
});
this.state.email
Validating properties:
NAME
Primative Types
Reactive Elements
boxFlex
Enumerables
boxFlexGroup
columnCount
fillOpacity
DESCRIPTION
.string
.number
.func
.bool
.element
.node
.oneOf
.oneOfType
.array[Of]
.object[Of]
.instanceOf
.shape
flex
Sample usage:
flexGrow
flexPositive
React.createClass({
propTypes: {
email: React.PropTypes.string,
firstName: React.PropTypes.string,
age: React.PropTypes.number,
gender: React.PropTypes.oneOf(['M','F','NA'])
node: React.PropTypes.node,
cb: React.PropTypes.func.isRequired,
}
});
flexShrink
flexNegative
fontWeight
lineClamp
lineHeight
opacity
order
Custom validation:
orphans
propTypes: {
customProp: function(props, propName, componentName) {
if (!/matchme/.test(props[propName])) {
return new Error('Validation failed!');
}
}
}
strokeOpacity
widows
zIndex
zoom
D Z O NE, INC .
DZ O NE .C O M
4
Property Initializers
REACT ADDONS
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 {
handleOptionsButtonClick = (e) => {
this.setState({showOptionsModal: true});
}
}
react-addons-clone-with-props
react-addons-create-fragment
react-addons-css-transition-group
react-addons-linked-state-mixin
react-addons-perf
react-addons-pure-render-mixin
react-addons-shallow-compare
react-addons-test-utils
react-addons-transition-group
react-addons-update
ReactDOM.unstable_batchedUpdates in react-dom
REACT.JS ESSENTIALS
var TimeOutMixin = {
componentWillMount: function() { .. }
}
REACT ON ES2015/ES6
NOTE: The following are experimental, and you must use a
transpiler for this to work.
Classes
class Animal extends React.Component {
render() {
return <img alt={this.props.name} src={this.props.src} />;
}
}
D Z O NE, INC .
tick: =>
@setState count: @state.count + 1
render: ->
div onClick: @tick,
'Clicks: '
@state.count
DZ O NE .C O M
REACT.JS ESSENTIALS
CO N V E N T I O N S F O R R E AC T D O M & J S X
A few patterns and best practices to get you started:
F L UX : T H E A P P L I C AT I O N A RC H I T E C T U R E
1.
ANTI-PATTERN
2.
3.
4.
Points to remember
1.
2.
3.
4.
A Store is a singleton.
5.
6.
7.
8.
C H A N G E S I N R E AC T V0.1 4
You can also use the spread operator (...) to override props:
D Z O NE, INC .
DZ O NE .C O M
REACT.JS ESSENTIALS
// sum.js
function div (value1, value2) {
return value1 / value2;
}
module.exports = sum;
1.
// __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.
3.
4.
T E S T I N G YO U R A P P L I C AT I O N W I T H J E S T
Just follow the above steps, and you are ready to run with Jest!
RESOURCES
HEMANTH H.M. has had exposure to major scripting languages throughout his career, and his
major focus in the last couple of years has been on frontend. He maintains strict discipline in
coding, likes to adopt TDD and Agile processes not only in his professional life, but also in all his
FOSS contributions. He is a core team member of the Google Yeoman project, and has published
many node modules and ruby gems and is a maintainer of many major projects. Currently he is
working heavily on Node.js, especially on expressjs and koajs.
His major area of interest and research is in ECMAScript, has delivered few talks w
ith JSChannel(Partners with
JSConf US) and JSFoo. H
e also co-organises BangaloreJS meetups and helps people to get into FOSS on IRC
and a few slack groups. He writes technical articles on his blog(400+ articles so far) his <3 towards Node made
him start nmotw.in (Node module of the week), which talks about a new interesting node module every week, also
started jsfeatures.in, which covers all the JavaScript features in a SPA.
React.js Website
React.js Documentation
React.js Download
Why React?
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
developers, architects and decision makers. DZone offers something for everyone, including news,
tutorials, cheat sheets, research guides, feature articles, source code and more.
888.678.0399
919.678.0300
REFCARDZ FEEDBACK WELCOME
[email protected]
SPONSORSHIP OPPORTUNITIES
DZ [email protected]
NE .C O M
Copyright 2016 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or
D Zpermission
O NE, INC
transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
of the. publisher.
VERSION 1.0