Introduction to React JS Presentation
What is React and what is not?
React is JavaScript library for creating user interface. React is not an MVC Framework and not a template library (no separation into template and controller). The goal of React is to build large applications with data that changes over time. So, how can I use it if it is not a framework? Easy:) with some other MVC or Flux frameworks.
React key concepts
Better to know some basic concepts of React to make our introduction smooth.
- React elements - JavaScript objects which represent browser HTML elements (h1, div, section …)
- Components - developer created React elements. Incapsulate some UI + functionality (NavBar, ImageUploader, Grid, PhotoGallery)
- JSX - xml-ish markup language for creating React elements, mix of html and javascript which is compiled to JavaScript. <div className=”people”> -> React.DOM.div({className: “people”})
- Virtual DOM - JavaScript tree of React elements in memory.
How does it work?
So, let's imagine we've created bunch of React components and add them to the web-page. What is React actually doing with them? How does it work in general? And what about the changes over time?
What React does with your components
- Build Virtual DOM from components
- Compile Virtual DOM to the string of markup
- Inject markup into document
How React applies changes
- Compare Virtual DOM before and after changes and find the diffs
- Generate a minimal set of changes to be applied to the DOM
- Apply changes
How to start
React is extremely easy to start, here is the easy way which is good to try React. If you going to use it in production I advice you to use npm or stuff like that.
- Include into your page react, react-dom, babel
- Create container element for your app #myapp
- Create component and render it to #myapp element
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="build/react.js"></script> /*react core*/
<script src="build/react-dom.js"></script> /*render components to dom*/
<script src="/babel-core/browser.min.js"></script> /*JSX rendering by Babel*/
</head>
<body>
<div id="example"></div>
<script>
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('example')
);
</script>
</body>
</html>
Component props
Better to think about props like component`s options, passed from the parent component. Props looks like HTML attributes and they are immutable
var Photo = React.createClass({
render: function() {
return (
<div className='photo'>
<img src={this.props.src} />
<span>{this.props.caption}</span>
</div>
);
}
});
ReactDOM.render(<Photo src='http://abc.com/r.jpg' caption='Abc' />,
document.body);
Component state
In comparison with props, state is mutable. State is an object which holds internal state of component and it is private. Do not update state directly, use setState method for this. Because of calling setState triggers component update (and thus render method), do not call setState within render method.
var Photo = React.createClass({
getInitialState: function() {
return { liked: false };
},
toggleLiked: function() {
this.setState({ liked: !this.state.liked });
},
render: function() {
var buttonClass = this.state.liked ? 'active' : '';
return (
<div className='photo'>
<img src={this.props.src} />
<div className='bar'>
<button onClick={this.toggleLiked} className={buttonClass}>
Like
</button>
<span>{this.props.caption}</span>
</div>
</div> ); }
});
Complex React component
Component is a building block of React application.What you should know about components:
- Components are reusable
- Render function can contain logic
- Main template can contain loops, filtering, ternary operators
var PhotoGallery = React.createClass({
render: function() {
var photos = this.props.photos.map(function(photo) {
return <Photo src={photo.url} caption={photo.caption} />
});
return (
<div className='photo-gallery'>
{photos.length > 0 ? photos : ''}
</div>
);
}
});
Component with user input
So, what should I do to get the data from my text box?
- Use ref to set unique element ID, for instance your text input
- Use refs to get data from element
- Use props to set component event handlers
Keep in mind, React uses camelCase to attach event handlers to synthetic events
var CommentForm = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var author = this.refs.author.value.trim();
var text = this.refs.text.value.trim();
if (!text || !author) { return; }
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.value = '';
this.refs.text.value = '';
return;
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" />
<input type="text" placeholder="Say something..." ref="text" />
<input type="submit" value="Post" />
</form> );
}
});
Synthetic events
React component use specific type of events for communication - synthetic events. Synthetic event is cross-browser wrapper around the browser's native event. It has the same interface as the browser's native events (like stopPropagation, preventDefault, etc). It works identically across all browsers.
Component Lifecycle Hooks
As any other framework React has set of hooks which can be used to do some preparation or clean-up. Most of the methods are done in pairs "conponentWillSmth" and "componentDidSmth" - before and after "Smth" operation accordingly. Their names pretty self-descriptive. So here they are:
- componentWillMount
- componentDidMount
- componentWillReceiveProps(nextProps)
- shouldComponentUpdate(nextProps, nextState)
- componentWillUpdate(nextProps, nextState)
- componentDidUpdate(prevProps, prevState)
- componentWillUnmount
What is a React Native?
React Native is framework for building mobile apps on native platforms using JavaScript + React. What can we get from such approach?
- Application logic is written and runs in JavaScript, application UI is fully native
- Learn once, write anywhere - iOS, Android, Web
- Uses CSS properties for styling
var App = React.createClass({
render: function() {
return (
<TabBarIOS>
<TabBarIOS.Item title="React Native" selected={true}>
<NavigatorIOS initialRoute={{ title: 'React Native' }} />
</TabBarIOS.Item>
</TabBarIOS>
);
}});
React strengths
- Performance (virtual DOM, shouldComponentUpdate)
- Extremely easy to start
- Server-side rendering
- Easy to read, maintain, debug
- Compatible with MVC frameworks (Backbone, Angular ...)
- Compatible with Flux frameworks (Flux, Reflux ...)
- Compatible with bundling systems (RequireJS, Browserify, WebPack)
- React Native on mobile
- Big community
- A lot of boilerplates
- A lot of ready-to-use components
React weaknesses
- No DI
- No event system
- No ajax helpers
- No any data layer
- No Futures
- No Routing (use third-party)
- Not an app framework
I've been working with React for 1 year and I can admit that it is awesome. If you going to start a new project (or maybe refactor existing one) and you are OK with their Licence Agreement I definitely advice you to give React a chance. Thank you for reading, below you can find my presentation in Google Docs.