Introduction
http://github.com/FrontendMasters/2015-02-13-React/
Will build an app live.
Uses commonJs.
creates app.js. Hello World example
// **** app.js ****
var React = require('react');
var App = React.createClass({
render () {
return (
<h1>Hello</h1>
);
}
})
React.render(<App/>, document.body);
Continues more complex example
// **** app.js ****
var React = require('react');
// 4. ++++ adds fetchUsers
var fetchUsres = (cb) => {
setTimeout(() => {
cb([{name:'Ryan'}, {name: 'Marc'}, {name: 'Mark'}])
}, 500)
}
var App = React.createClass({
// 1. ++++ let's fetch a list of users
getInitialState () {
return {
users: [],
loaded: false
}
},
// 3. ++++ Adds lifecycle event
componentDidMount () {
fetchUsers(users) => {
this.setState({
users,
loaded: true
});
}
}
render () {
// 2. ++++ Don't render if we didn't get anything
if (!this.state.loaded) {
return <div>Loading</div>;
}
// 6. ++++ defines users
var users = this.state.users.map((user) => {
return <li>{user.name}</li>
});
return (
// 5. ++++ list users
<div>
<h1>Hello</h1>
<ul>
{users}
</ul>
<div>
);
}
})
React.render(<App/>, document.body);
His browser immediately displays the rendered list of users.ES6 syntax
Webpack comes with a transpiler.
Arrow functions
the
this
keyword will be global scoped (clarified because the syntax looks like Coffeescript where this
would scope to the function.Function notation
Add a function as an object property
{getInitialState () {..};}
Destructuring
this.setState({users})
same as this.setState({users:users})
Webpack settings
Shows settings in webpack to transpile to ES5.
webpack.config.js:
// webpack.config.js
..
module: {
loaders: [
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.js$/, loader: 'jsx-loader?harmony' }
]
},
..
Adds the ability to delete a person:
// **** app.js ****
var React = require('react');
var fetchUsres = (cb) => {
setTimeout(() => {
cb([{name:'Ryan'}, {name: 'Marc'}, {name: 'Mark'}])
}, 500)
}
var App = React.createClass({
getInitialState () {
return {
users: [],
loaded: false
}
},
componentDidMount () {
fetchUsers(users) => {
this.setState({
users,
loaded: true
});
}
},
// 2. ++++ deletUsers handler
deleteUsers(target) {
var users = this.state.users;
var withoutUsers = users.filter(user => user.name !== target.name);
this.setState({ users: withoutUsers});
}
render () {
if (!this.state.loaded) {
return <div>Loading</div>;
}
var users = this.state.users.map((user) => {
// 1. ++++ add onclick handler
return <li onClick={this.deleteUsers.bind(this, user)}>{user.name}</li>
});
return (
<div>
<h1>Hello</h1>
<ul>
{users}
</ul>
<div>
);
}
})
React.render(<App/>, document.body);