Professional Documents
Culture Documents
Giuseppe Attardi
Università di Pisa
What is React
local
view controller model
React: browser
view controller model
No MVC, just V
In traditional MVC different parts of the UI
talk via events, with a controller receiving
all the user inputs, manipulating the models
if needed and then calling the views and
telling them to re-render if necessary.
In React, when a user interaction occurs,
everything is re-rendered
Separation between code and presentation
vanishes (again …)
Components are single units, they can be
instantiated and moved without having to
reconnect them to handlers (e.g. in
jQuery.readyFunction)
Virtual DOM
React JSFiddle
React Tutorial
JSX
JSX is a JavaScript syntax extension that
looks similar to XML
<div className="red">Children Text</div>;
React.createElement(“Dashboard”,
{ "data-index": "2" },
React.createElement("h1", null, "Scores"),
React.createElement(”Scoreboard”, {
className: "results", scores: scores })
);
Transform
<div>{this.props.message}</div>;
Exercise
The component VacancySign should render a
div with either the text "Vacancy" or "No
Vacancy" depending on the prop hasVacancy.
View Solution
Events
var BannerAd = React.createClass({
onBannerClick: function(evt) {
// codez to make the moneys
},
render: function() {
// Render the div with an onClick prop (value is a function)
return <div onClick={this.onBannerClick}>Click Me!</div>;
}
});
Exercise
var ChildComponent = React.createClass({
render: function() {
return <div>
<button>Do Magic</button> // invoke performMagic in parent
</div>; }
});
var ParentComponent = React.createClass({
performMagic: function() { alert('TAADAH!'); },
render: function() { return <div> <ChildComponent /></div>; }
});
ReactDOM.render( <ParentComponent />,
document.getElementById('container')
);
View Solution
State
See example.
Like Button
var LikeButton = React.createClass({
getInitialState: function() { return { liked: false }; },
handleClick: function(event) { this.setState({liked: !this.state.liked}); },
render: function() {
var text = this.state.liked ? 'like' : ‘might like';
return (
<p onClick={this.handleClick}>
You {text} this. Click to toggle.
</p>
);
}
});
ReactDOM.render(
<LikeButton />,
document.getElementById('example')
);
API
getInitialState: function()
– returns dictionary
this.state
this.setState
– merges key/values into state
– triggers render()
Conclusions
React JS unifies behavior and
representation in single units called
components
Code generation in JSX is exploited to
provide a DSL for expressing elements
of the UI
Pure JavaScript solution, without
templating engine
Programmer is in full control of the UI
Components will eventually become
part of browser capabilities
ChatRoom Client
var UsersList = React.createClass({
render() {
return (
<div className='users'>
<h3> Online Users </h3>
<ul> {
this.props.users.map((user, i) => {
return (<li key={i}> {user} </li>); })
}</ul>
</div>
);
}});
var Message = React.createClass({
render() {
return (
<div className="message">
<strong>{this.props.user} :</strong>
<span>{this.props.text}</span>
</div>
);
}});
SocketIo
var app = express();
var server = http.createServer(app);
/* Socket.io Communication */
var io = require('socket.io').listen(server);
io.sockets.on('connection', socket);
/* Start server */
server.listen(app.get('port'), function (){
console.log('Express server listening on port %d in %s
mode',
app.get('port'),
app.get('env'));});
ChatApp
var ChatApp = React.createClass({
getInitialState() {
return {users: [], messages:[],
text: ''};
},
componentDidMount() {
socket.on('init', this._initialize);
socket.on('send:message',
this._messageRecieve);
socket.on('user:join', this._userJoined);
socket.on('user:left', this._userLeft);
socket.on('change:name',
this._userChangedName);
},
MessageReceive
_messageRecieve(message) {
var {messages} = this.state;
messages.push(message);
this.setState({messages});
},
Render
render() {
return (
<div>
<UsersList users={this.state.users} />
<MessageList messages={this.state.messages}/>
<MessageForm
onMessageSubmit={this.handleMessageSubmit}
user={this.state.user}
/>
<ChangeNameForm
onChangeName={this.handleChangeName}
/>
</div>
);
}});