ReactJS an Intro
Vijayakanth MDevOps EngineerMegam Systems
1
AGENDA
2
1. What is ReactJS and Why ?
2. ReactJS with JSX
3. Lifecycle Methods (specs and state)
4. Some code
5. Installation and Config
3
❖ ReactJS is a JavaScript Library for creating user interfaces by Facebook and Instagram.
❖ ReactJS is a building block of Components.❖ In ReactJS, application data flows unidirectionally via the state and
props objects, contrast to frameworks like Angular and Ember.❖ ReactJS runs a “diffing” algorithm, which identifies that has changed.❖ This will serve purely as an API endpoint which we'll use for getting and
saving data.
What is ReactJS ?
4
Flow of ReactJS
MVC Process ReactJS Flux Process
Why do we use ReactJS ?
❖ ReactJS is extremely fast, because it uses virtual DOM, and syncs only the changed parts.
❖ React.js uses a special syntax called JSX, which allows you to mix HTML with JavaScript.
❖ When the data changes, ReactJS conceptually hits the "refresh" button, and knows to only update the changed parts.
❖ React is all about building reusable components.❖ It is much smaller and plays nicely with jQuery and other frameworks.
6
ReactJS with JSX
❖ JSX is a JavaScript syntax extension that looks similar to XML. You can use a simple JSX syntactic transform with React.
❖ React JSX transforms from an XML-like syntax into native JavaScript.
var Nav, Profile;// Input (JSX):var app = <Nav color="blue"><Profile>click</Profile></Nav>;// Output (JS):var app = React.createElement( Nav, {color:"blue"}, React.createElement(Profile, null, "click"));
7
Now see a simple structure of ReactJS Component
var MyComponent = React.createClass({render: function(){return (<h1>Hello, world!</h1><CommentList />);}});
How to call the Components in Rails
<% react_component ‘MyComponent’ %>
var CommentList = React.createClass({render: function() {return (<div className="commentList"> <h1> I am a CommentList. </h1></div>);}});
Every Component must have a render function, it will return an another react Component or tags
8
Lifecycle Methods, Specs and State
8
componentWillMount Invoked once, on both client & server before rendering occurs.
componentDidMount Invoked once, only on the client, after rendering occurs.
shouldComponentUpdate Return value determines whether component should update
componentWillUnmount Invoked prior to unmounting component.
9
continue….
StateEvery component has a state object and a props object. State is set using the setState method. Calling setState triggers UI updates and is the bread and butter of React’s interactivity. If we want to set an initial state before any interaction occurs we can use the getInitialState method.
getInitialState Return value is the initial value for state.
getDefaultProps Sets fallback props values if props aren’t supplied.
Specs
10
some code//Child componentvar Comment = React.createClass({render: function() {return (<div className="comment"><h2 className="commentAuthor">{this.props.author}</h2>{this.props.children}</div>); } });
//Parent componentvar CommentList = React.createClass({render: function() {return (<div className="commentList"><Comment author="Pete Hunt">This is one comment</Comment><Comment author="Jordan Walke">This is *another* comment</Comment></div>);}});
<%= react_component ‘CommentList’ %> Note that we have passed some data from the parent CommentList component to the child Comment components. For example, we passed PeteHunt (via an attribute) and This is one comment (via an XML-like child node) to the first Comment. As noted above, the Comment component will access these 'properties' through this.props.author, and this.props.children.
11
var data = [{author: "Pete Hunt", text: "This is one comment"},{},...}];
var CommentBox = React.createClass({loadCommentsFromServer: function() {$.ajax({ //… Make a ajax call to get data from server}); }, getInitialState: function() { return {data: []};}, // to get data continuous
componentDidMount: function() {this.loadCommentsFromServer();setInterval(this.loadCommentsFromServer, this.props.pollInterval);},
// Render another Components
render: function() {return (<div className="commentBox"><h1>Comments</h1><CommentList data={this.state.data} /></div>);} });
Data from the server
12
continue... // To list all data get from the server
var CommentList = React.createClass({render: function() {var commentNodes = this.props.data.map(function (comment) {return (<Comment author={comment.author}>{comment.text}</Comment>);});return (<div className="commentList">{commentNodes}</div>);}
var Comment = React.createClass({render: function() {return (<div className="comment"><h2 className="commentAuthor">{this.props.author}</h2>{this.props.children}</div>);}});
13
continue...
<%= react_component ‘CommentBox’ url: “/json”, timeInterval: 4000 %>
Or<script type="text/javascript">ReactDOM.render( ReactDOM.render(React.createElement(NewOverview, { url: “/json”, timeInterval:4000}), document.getElementById('content') );</script>
Write the Component code in : app/assets/javascripts/components/<filename>.js.jsx
the calling command on:
app/views/<directory name>/<htmlerbfile>.html.erb
The flow of the Program
14
Flow of above Components CommentBox //Parent component
getInitialState { } loadCommentsFromServer{ $.ajax({ //… Make a ajax call to get data }); }, componentDidMount {setInterval( Get synchronous ajax call to get data) }
CommentList //Child component Map{ // fetch each data from whole json and send to component }
Comment //Child component
render: { return ( Call children components and send data)}
render: { return ( call Comment component)}
render: { return ( Show all data )}
15
continue...EventsReact attaches event handlers(onSubmit) to components using a camelCase naming convention.
Call preventDefault() on the event to prevent the browser's default action of submitting the form.
Refs We use the ref attribute to assign a name to a child component and this.refs to reference the component. We can call React.findDOMNode(component) on a component to get the native browser DOM element.
Callbacks as propsWe need to pass data from the child component back up to its parent. We do this in our parent's render method by passing a new callback ( handleCommentSubmit) into the child, binding it to the child's onCommentSubmit event. Whenever the event is triggered, the callback will be invoked:
16
Installation and Config
Add react-rails to your gemfile:
gem 'react-rails', '~> 1.3.0'
Next, run the installation script:
rails g react:install
place the following in your application.js(app/assets/javascripts/):
//= require react//= require react_ujs//= require components
You can pick which React.js build (development, production, with or without add-ons) to serve in each environment by adding a config.
# config/environments/development.rbMyApp::Application.configure do config.react.variant = :developmentend
# config/environments/production.rbMyApp::Application.configure do config.react.variant = :productionend
Questions...
18
Vijayakanth MDevOps EngineerMegam Systems(www.megam.io)
Twitter: @vijayakanth_mpEmail: [email protected]
Docs: docs.megam.ioDevcenter: Devcenter.megam.io
Thank you…
Top Related