8.9 KiB
title | category | layout |
---|---|---|
React.js | React | 2017/sheet |
{%raw%}
Example
{: .-left-reference}
Basic example
class Hello extends React.Component {
render () {
return <div className='message-box'>
Hello {this.props.name}
</div>
}
}
const el = document.body
ReactDOM.render(<Hello name='John' />, el)
Use the React.js jsfiddle to start hacking. (or the unofficial jsbin).
Try it
Open in jsbin {: target="_blank"}
Components
{: .-three-column}
Class components
class MyComponent extends React.Component {
render () {
return <div className='message-box'>
Hello {this.props.name}
</div>
}
}
const el = document.body
ReactDOM.render(<MyComponent name='John' />, el)
Functional components
function MyComponent ({ name }) {
return <div className='message-box'>
Hello {name}
</div>
}
Functional components have no state. Also, their props
are passed as the first parameter to a function.
Nesting
class Info extends React.Component {
render () {
const { avatar, username } = this.props
return <div>
<UserAvatar src={avatar} />
<UserProfile username={username} />
</div>
}
}
Nest components to separate concerns. See: multiple components
Component API
this.forceUpdate()
this.setState({ ... })
this.replaceState({ ... })
this.state
this.props
These methods and properies are available for Component
instances. See Component API.
Properties
<Video fullscreen={true} />
class Video extends React.Component {
render () {
this.props.fullscreen
/* ... */
}
}
Use props (this.props
) to access parameters passed from the parent.
States
this.setState({ username: 'rstacruz' })
render () {
this.state.username
/* ... */
}
Use states (this.state
) to manage dynamic data.
See States.
Setting default props
Hello.defaultProps = {
color: 'blue'
}
See defaultProps.
Setting default state
class Hello extends React.Component {
constructor (props) {
super(props)
this.state = { visible: true }
}
}
Lifecycle
{: .-two-column}
Mounting
| constructor
(props) | Before rendering # |
| componentWillMount()
| Don't use this # |
| render()
| Render # |
| componentDidMount()
| After rendering (DOM available) # |
| componentWillUnmount()
| Before DOM removal # |
Set initial the state on constructor()
.
Add DOM event handlers, timers (etc) on componentDidMount()
, then remove them on componentWillUnmount()
.
Updating
| componentWillReceiveProps
(newProps) | Use setState()
here |
| shouldComponentUpdate
(newProps, newState) | Skips render()
if returns false |
| componentWillUpdate
(newProps, newState) | Can't use setState()
here |
| render()
| Render |
| componentDidUpdate
(prevProps, prevState) | Operate on the DOM here |
Called when parents change properties and .setState()
. These are not called for initial renders. See reference.
DOM nodes
{: .-two-column}
References
class MyComponent extends React.Component {
render () {
return <div>
<input ref={el => this.input = el} />
</div>
}
}
this.input.focus()
this.input.value()
Allows access to DOM nodes. See Refs and the DOM.
DOM Events
<input type="text"
value={this.state.value}
onChange={this.handleChange} />
handleChange: function(event) {
this.setState({ value: event.target.value });
}
Add attributes like onChange
. See events.
Property validation
{: .-three-column}
React.PropTypes
PropType | Description |
---|---|
any |
Anything |
--- | --- |
string |
|
number |
|
func |
Function |
bool |
True or false |
--- | --- |
oneOf (any) |
Enum types |
oneOfType (type array) |
Union |
--- | --- |
array |
|
arrayOf (...) |
|
--- | --- |
object |
|
objectOf (...) |
|
instanceOf (...) |
|
shape (...) |
|
--- | --- |
element |
React element |
node |
DOM node |
--- | --- |
.isRequired |
Required |
See propTypes.
Basic types
MyComponent.propTypes = {
email: React.PropTypes.string,
seats: React.PropTypes.number,
callback: React.PropTypes.func,
isClosed: React.PropTypes.bool,
any: React.PropTypes.any
}
Required types
MyCo.propTypes = {
name: React.PropTypes.string.isRequired
}
Elements
MyCo.propTypes = {
// React element
element: React.PropTypes.element,
// num, string, element, or an array of those
node: React.PropTypes.node
}
Enumerables (oneOf)
MyCo.propTypes = {
direction: React.PropTypes.oneOf([
'left', 'right'
])
}
Arrays and objects
MyCo.propTypes = {
array: React.PropTypes.array,
arrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
object: React.PropTypes.object,
objectOf: React.PropTypes.objectOf(React.PropTypes.number),
message: React.PropTypes.instanceOf(Message),
object2: React.PropTypes.shape({
color: React.PropTypes.string,
size: React.PropTypes.number
})
}
Use .array[Of]
, .object[Of]
, .instanceOf
, .shape
.
Custom validation
MyCo.propTypes = {
customProp: (props, key, componentName) => {
if (!/matchme/.test(props[key])) {
return new Error('Validation failed!')
}
}
}
Other features
Transfering props
<VideoPlayer src="video.mp4" />
class VideoPlayer extends React.Component {
render () {
return <VideoEmbed {...this.props} />
}
}
Propagates src="..."
down to the sub-component.
See Transferring props.
Top-level API
React.createClass({ ... })
React.isValidElement(c)
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
JSX patterns
{: .-two-column}
Style shorthand
var style = { height: 10 }
return <div style={style}></div>
See inline styles.
Inner HTML
function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />
See dangerously set innerHTML.
Lists
class TodoList extends React.Component {
render () {
const { items } = this.props
return <ul>
{items.map(item =>
<TodoItem item={item} key={item.key} />)}
</ul>
}
}
Always supply a key
property.
Conditionals
<div>
{showPopup
? <Popup />
: null}
</div>
Also see
{: .-one-column}
This reference was made for React v15.
- React website (facebook.github.io)
- Animations (facebook.github.io)
{%endraw%}