References
Helps to access the DOM nodes.
<input ref="firstName">
this.refs.firstName
React.findDOMNode(this.refs.firstName).focus()
React.findDOMNode(this.refs.firstName).value
DOM Events: Helps to handle DOM events.
<input type="text" value={this.state.value} onChange={this.handleChange} />
handleChange: function(event) {
this.setState({ value: event.target.value });
}
Two-way data bindings with mixins
Email: <input type="text" valueLink={this.linkState('email')} />
React.createClass({
mixins: [React.addons.LinkedStateMixin]
});
this.state.email
Validating properties
Primitive types: .string, .number, .func, and .bool.
React elements: .element, .node.
Enumerables: .oneOf, .oneOfType.
Arrays and objects: array[Of], .object[Of], .instanceOf, .shape.
Sample usage:
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,
}
});
Custom Validation
propTypes: {
customProp: function(props, propName, componentName) {if (!/matchme/.test(props[propName])) {return new Error('Validation failed!');}
}
}
React Addons
React.addons are useful utilities for building React apps, these are currently experimental, and not yet part of Core React.
-
TransitionGroup and CSSTransitionGroup, for dealing with animations and transitions
-
LinkedStateMixin helps in two way data binding.
-
cloneWithProps, to make shallow copies of React components and change their props.
-
createFragment, helps to create a set of externally-keyed children.
-
update, helps to deal with immutable data.
-
PureRenderMixin, a performance booster under certain situations.
Apart from these there are few which are available in the development (unminified) version of React only:
-
TestUtils, simple helpers for writing test cases
-
Perf, for measuring performance and giving you hint where to optimize.
To get the add-ons, use react-with-addons.js (and its minified counterpart) rather than the common react.js.
When using the react package from npm, simply require('react/addons') instead of require('react') to get React with all of the add-ons.
NOTE: Add-ons have moved to separate packages in React v0.14+:
- 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
Creating Your Own Mixins
var TimeOutMixin = {
componentWillMount: function() { .. }
}
var TickTock = React.createClass({
mixins: [TimeOutMixin]
}
React on ES2015/ES6:
These 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} />;
}
}
Property Initializers
var Video = React.createClass({
getDefaultProps: function() {
return {
autoPlay: false,
maxLoops: 10,
};
},
getInitialState: function() {
return {
loopsRemaining: this.props.maxLoops,
};
},
propTypes: {
autoPlay: React.PropTypes.bool.isRequired,
maxLoops: React.PropTypes.number.isRequired,
posterFrameSrc: React.PropTypes.string.isRequired,
videoSrc: React.PropTypes.string.isRequired,
},
});
Arrow Functions
class PostInfo extends React.Component {
handleOptionsButtonClick = (e) => {
this.setState({showOptionsModal: true});
}
}
Dynamic property names with template strings
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 <PostsGrid {...others} />
}
}
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
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}
{{ parent.urlSource.name }}