Q1: What is ReactJS? What are the advantages of using ReactJS
and how it’s different from other JavaScript Frameworks? What are its
limitations?
React is an open source JavaScript front end UI library
developed by Facebook for creating interactive, stateful & reusable
UI components for web and mobile app. It is used by Facebook, Instagram and
many more web apps.
ReactJS is used for handling view layer for web and mobile
applications. One of React’s unique major points is that it perform not
only on the client side, but also can be rendered on server side, and they can
work together inter-operably.
Advantages of ReactJS:
React uses virtual DOM which is JavaScript object. This improves
application performance as JavaScript virtual DOM is faster than the regular
DOM.
§
React can be used on client and as well as server side too.
§
Using React increases readability and makes maintainability
easier. Component, Data patterns improves readability and thus makes it easier
for manitaing larger apps.
§
React can be used with any other framework (Backbone.js,
Angular.js) as it is only a view layer.
§
React’s JSX makes it easier to read the code of our component.
It’s really very easy to see the layout. How components are interacting,
plugged and combined with each other in app.
Limitations of ReactJS:
§
React is only for view layer of the app so we still need the
help of other technologies to get a complete tooling set for development.
§
React is using inline templating and JSX. This can seem awkward
to some developers.
§
The library of react is too large.
§
Learning curve for ReactJS may be steep.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<!DOCTYPE html>
<html lang="en">
<head><title>Web
Development Tutorial - React Example</title></head>
<body>
<div
id="hello-web"></div>
<script
src="https://fb.me/react-15.0.0.js"></script>
<script
src="https://fb.me/react-dom-15.0.0.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script
type="text/babel">
var
HelloWeb = React.createClass({
render:
function() {
return
( <p>Hello, WebDevTutorial</p> )
}
});
ReactDOM.render(
<HelloWeb/>, document.getElementById('hello-web'));
</script>
</body>
</html>
|
Q2: Please explain step by step approach on how to setup
environment for ReactJS?
Next we will discuss how to set up environment for React.js
successful development.
For this we will be
needing NodeJS so if not installed, below its mentioned
how to install nodejs?
§
Step 1: Download and Install NodeJs
To Verify installation: Create a js file named Test.js on your machine (Either on Windows or Linux) and try the below mentioned code.
To Verify installation: Create a js file named Test.js on your machine (Either on Windows or Linux) and try the below mentioned code.
1
2
|
/* Hello, World! program in
node.js */
console.log("Hello,
World!")
|
Execute/run test.js file using Node.js interpreter to see the
below result:
1
2
|
$ node test.js
Hello, World!
|
§
Step 2: Installing Global Packages
We need to install several packages for setting up of environment.We will be needing some of the babel plugins.
We need to install several packages for setting up of environment.We will be needing some of the babel plugins.
1
2
|
user@administrator:/var/www/html/reactjs$
npm install -g babel
user@administrator:/var/www/html/reactjs$
npm install -g babel-cli
|
§
Step 3: Create Root Folder
1
2
|
user@administrator:/var/www/html/reactjs$
mkdir reactApp
user@administrator:/var/www/html/reactjs/reactApp$
npm init
|
§
Step 4: Add Dependencies and Plugins
1
2
|
user@administrator:/var/www/html/reactjs$
npm install webpack –save
user@administrator:/var/www/html/reactjs$
npm install webpack-dev-server --save
|
Since we want to use React, we need to install it first.
The –save command will add these packages to package.json file.
1
2
|
user@administrator:/var/www/html/reactjs/reactApp$
npm install react --save
user@administrator:/var/www/html/reactjs/reactApp$
npm install react-dom --save
|
We already mentioned that we will need some babel plugins so let’s install it too.
1
2
3
4
|
user@administrator:/var/www/html/reactjs/reactApp$
npm install babel-core
user@administrator:/var/www/html/reactjs/reactApp$
npm install babel-loader
user@administrator:/var/www/html/reactjs/reactApp$
npm install babel-preset-react
user@administrator:/var/www/html/reactjs/reactApp$
npm install babel-preset-es2015
|
§
Step 5: Create App files for ReactJs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
user@administrator:/var/www/html/reactjs/reactApp$
touch index.html App.jsx main.js webpack.config.js
user@administrator:/var/www/html/reactjs/reactApp$
vim webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
File: index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "index.js"></script>
</body>
</html>
File: App.jsx
import React from 'react';
class ReactApp extends React.Component
{
render() {
return (
<div>
Hello World ReactJS!!!
</div>
);
}
}
export default App;
File: main.js
import React from 'react';
import ReactDOM from 'react-dom';
import ReactApp from './App
.jsx';
ReactDOM.render(<App />,
document.getElementById('app'));
|
§
Step 6: Running the Server
1
|
user@administrator:/var/www/html/reactjs/reactApp$
npm start
|
Q3:
What is ReactJS-JSX? What are the advantages of using JSX? Explain basic code
snippet of JSX with the help of a practical example?
JSX (JavaScript XML), lets
us to build DOM nodes with HTML-like syntax. JSX is a preprocessor step which
adds XML syntax to JavaScript.
Like XML, JSX tags have a
tag name, attributes, and children JSX also has the same. If an
attribute/property value is enclosed in quotes(“”), the value is said to be
string. Otherwise, wrap the value in braces and the value is the enclosed JavaScript
expression. We can represent JSX as <HelloWorld/>.
JSX is completely optional and its not mandatory, we don’t need
to use it in order to use React, but it has several advantages and a lot
of nice features in JSX.
§
JSX is always faster as it performs optimization while compiling
code to vanilla JavaScript.
§
JSX is also type-safe, means it is strictly typed and most
of the errors can be caught during compilation of the JSX code to JavaScript.
§
JSX always makes it easier and faster to write templates if we
are familiar with HTML syntax.
Our browsers does not understand JSX code natively, we need to
convert it to JavaScript first which can be understand by our browsers. We have
aplugin which handles including Babel 5’s in-browser ES6 and JSX transformer
called browser.js.
Babel will understand and recognize JSX code in <script
type=”text/babel”></script> tags and transform/convert it to
normal JavaScript code.
In case of production we will need to pre-compile our JSX code
into JS before deploying to production environment so that our app renders
faster.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<!DOCTYPE html>
<html lang="en">
<head><title>My First React JSX Example</title></head>
<body>
<div id="hello-world"></div>
<script src="https://fb.me/react-15.0.0.js"></script>
<script src="https://fb.me/react-dom-15.0.0.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<script type="text/babel">
var HelloWorld = React.createClass({
render: function() {
return ( <p>Hello, World</p> )
}
});
ReactDOM.render( <HelloWorld/>,
document.getElementById('hello-world'));
</script>
</body>
</html>
|
Q4:
What are Components in ReactJS? Explain the Component Lifecycle with the help
of a diagram explaining each component method in detail. Also, Give an example
of both Stateless and Stateful components with source code?
React encourages the idea of reusable components. They are
widgets or other parts of a layout (a form, a button, or anything that can be
marked up using HTML) that you can reuse multiple times in your web
application.
ReactJS enables us to
create components by invoking the React.createClass()
method features a render() method
which is responsible for displaying the HTML code.
When designing interfaces, we have to break down the individual
design elements (buttons, form fields, layout components, etc.) into reusable
components with well-defined interfaces. That way, the next time we need to
build some UI, we can write much less code. This means faster development time,
fewer bugs, and fewer bytes down the wire.
Component Lifecycle Methods
§
getDefaultProps and getInitialState, both
methods are called only once while initially rendering of the component.
§
componentWillMount : This
method is executed just before rendering on both client and server side.
§
ComponentDidMount: This
method is executed after first rendering only on the client side. This is where
AJAX requests and DOM or state updates usually occurs. This method is also used
for integration with other JavaScript frameworks.
§
ComponentWillReceiveProps: This
method is invoked as soon as the props are updated before another render is
called.
§
ShouldComponentUpdate: This
method should return true or false value. This determines whether if a
component will be updated or not. Default it is set to true.
§
ComponentWillUpdate: This
method is called just before rendering.
§
ComponentDidUpdate: This
method is called just after rendering.
§
ComponentWillUnmount: This
method is called after the component is unmounted from the DOM.
Stateless and Stateful components
Stateless: When
a component is “stateless”, it calculates state is calculated internally but it
directly never mutates it. With the same inputs, it will always produce the same output. It means it has no
knowledge of the past, current or future state changes.
1
2
3
4
5
6
|
var React = require('react');
var Header = React.createClass({
render: function() {
return( <img src={this.props.imageSource} /> ); }
});
ReactDOM.render(<Header
imageSource="myImage.png"/>, document.body);
|
Stateful :
When a component is “stateful”, it is a central point that stores every
information in memory about the app/component’s state, do has the ability to
change it. It has knowledge of past, current and potential future state
changes.
Stateful component change the state, using this.setState method.
Stateful component change the state, using this.setState method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
var React = require('react');
var Header = React.createClass({
getInitialState: function() {
return { imageSource: "header.png" };
},
changeImage: function() {
this.setState({imageSource: "changeheader.png"});
},
render: function() {
return(
<img src={this.state.imageSource} onClick={this.changeImage.bind(this)}
/>
);
}
});
module.exports = Header;
|
Q5:
What are State and Props in ReactJS? What is the difference between the two?
Give a proper example of using State and Props to elaborate the concept with
complete source code?
State is
the place where the data comes from. We must follow approach to make our
state as simple as possible and minimize number of stateful components.
For example, ten components that need data from the state, we
should create one container component that will keep the state for all of them.
The state starts with a default value and when a
Component mounts and then suffers from mutations in time (basically generated from user events).
A Component manages its
own state internally, but—besides setting an initial
state—has no business fiddling with the stateof its
children. You could say the state is private.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import React from 'react';
import ReactDOM from 'react-dom';
var StepCounter = React.createClass({
getInitialState: function() {
return {counter: this.props.initialCount};
},
handleClick: function() {
this.setState({counter: this.state. counter + 1});
},
render: function() {
return <div onClick={this.handleClick}>{this.state.counter
}</div>;
}
});
ReactDOM.render(< StepCounter
initialCount={7}/>, document.getElementById('content'));
|
Props:
They are immutable, this is why container component should define state
that can be updated and changed. It is used to pass data down from our
view-controller(our top level component).
When we need immutable data in our component we
can just add props to reactDOM.render() function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import React from 'react';
import ReactDOM from 'react-dom';
class PropsApp extends React.Component
{
render() {
return (
<div>
<h1>{this.props.headerProperty}</h1>
<h2>{this.props.contentProperty}</h2>
</div>
);
}
}
ReactDOM.render(<PropsApp
headerProperty = "Header from props..." contentProperty = "Content
from
props..."/>, document.getElementById('app'));
}
|
|
Props
|
State
|
|
Passes in from
parent component.<PropsApp headerProperty = “Header from props…”
contentProperty = “Content from props…”/>This properties are
being read by PropsApp component and sent to ReactDOM View.
|
Created inside
component by getInitialState.this.state reads the property of component and
update its value it by this.setState() method and then returns to ReactDOM
view.State is private within the component.
|
The Complete React Native and Redux Course
iOS and Android App Development from scratch – build fully native mobile apps ridiculously fast! Get up and running with React Native quickly, and teach the core knowledge you need to deeply understand and build React components for mobile devices.
iOS and Android App Development from scratch – build fully native mobile apps ridiculously fast! Get up and running with React Native quickly, and teach the core knowledge you need to deeply understand and build React components for mobile devices.
React Native:
Advanced Concepts
Master the advanced topics of React Native: Animations, Maps, Notifications, Navigation and More! Go beyond the basics of React Native! This course will teach you the advanced topics you need to make a #1 best-selling app.
Master the advanced topics of React Native: Animations, Maps, Notifications, Navigation and More! Go beyond the basics of React Native! This course will teach you the advanced topics you need to make a #1 best-selling app.
Q6:
How to apply validation on Props in ReactJS? Apply validation in previously
developed example in above question?
When the application is running in development mode, React will
automatically check for all props that we set on components to make sure
they must right correct and right data type.
For instance, if we say a component has a Message prop which is
a string and is required, React will automatically check and warn if it
gets invalid string or number or boolean objects. For performance reasons this
check is only done on dev environments and on production it is disabled
so that rendering of objects is done in fast manner .
Warning messages are generated easily using a
set of predefined options such as:
§
React.PropTypes.string
§
React.PropTypes.number
§
React.PropTypes.func
§
React.PropTypes.node
§
React.PropTypes.bool
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import React from 'react';
import ReactDOM from 'react-dom';
class PropsValidation extends
React.Component {
render() {
return ( <div>
<h1>Propert Validation in ReactJS to validate Element Property
type</h1>
{this.props.children} </div>
);
}
}
PropsValidation.propTypes = {
children: React.PropTypes.node,
};
export default PropsValidation;
|
Execute the above example, when wrong prop type
is being detected it generate error message in console, try
using React.PropTypes.string in the code above and we will see
that our page still loads fine, but an error message in console.
Back to Top
Back to Top
Q7:
How to use Forms in ReactJS? Give an example of using Forms in ReactJS by
developing a User Registration Form?
In React’s virtual DOM, HTML Input element presents an
interesting problem. With the others DOM environment, we can render the
input or textarea and thus allows the browser maintain its state
that is (its value). we can then get and set the value implicitly with the DOM
API.
In HTML, form elements
such as <input>, <textarea>, and <select>
itself maintain their own state and update its state based on the
input provided by user .In React, components’ mutable state is handled by the
state property and is only updated by setState().
§
HTML
<input> and <textarea> components use
the value attribute.
§
HTML <input> checkbox and radio components,
checked attribute is used.
§
<option> (within <select>) components,
selected attribute is used for select box.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
var AccountFields = React.createClass({
render: function() {
return ( <div>
<div> <label>Name</label> </div>
<div> <input type="text"
ref="name"
defaultValue='Imran' /></div>
<div> <label>Password</label></div>
<div><input type="password"
ref="password"
defaultValue='' /></div>
<div> <label>Email</label></div>
<div><input type="email"
ref="email"
defaultValue='test.example.com'
/></div>
<button onClick={ this.saveAndContinue }>Save and Continue</button></div>
)
},
saveAndContinue: function(e) {
console.log(this.refs);
}
});
ReactDOM.render( <AccountFields />, document.getElementById('content') );
|
Q8:
How to use Events in ReactJS? Give an example of using events?
React identifies every
events so that it must have common and consistent behavior across
all the browsers. Normally, in normal JavaScript or other frameworks, the onchange event is triggered after we have typed
something into a Textfield and then “exited out of it”. In ReactJS we
cannot do it in this way.
The explanation is typical and non-trivial:
*”<input type=”text”
value=”dataValue”> renders an input textbox initialized with the
value, “dataValue”.
When the user changes the
input in text field, the node’s value property will update and change.
However, node.getAttribute(‘value’) will still return the value used
at initialization time that is dataValue.
Form Events:
§
onChange:
onChange event watches input changes and update state accordingly.
§
onInput: It is triggered on
input data
§
onSubmit: It is triggered on
submit button.
Mouse Events:
§
onClick: OnClick of any
components event is triggered on.
§
onDoubleClick:
onDoubleClick of any components event is triggered on.
§
onMouseMove: onMouseMove of any
components, panel event is triggered on.
§
onMouseOver: onMouseOver of any
components, panel, divs event is triggered on.
Touch Events:
§
onTouchCancel: This
event is for canceling an events.
§
onTouchEnd: Time Duration attached
to touch of a screen.
§
onTouchMove: Move during touch
device .
§
onTouchStart: On touching a device
event is generated.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import React from 'react';
import ReactDOM from 'react-dom';
var StepCounter = React.createClass({
getInitialState: function() { return {counter: this.props.initialCounter
}; },
handleClick: function() {
this.setState({counter:
this.state.counter + 1}); },
render:
function() {
return <div onClick={this.handleClick}> OnClick Event, Click
Here: {this.state.counter }</div>;
}
});
ReactDOM.render(< StepCounter
initialCounter={7}/>, document.getElementById('content'));
|
Q9:
How to set up routing in ReactJS. Explain with the help of step by step
approach?
Routing is the key features of web applications (and even
other platforms) could not be left out in React. We can develop full featured
single page applications (SPA) with React, one of the key feature is routing.
We use library called React-Router for routing in reactJS. React
goodness is to keep things as simple as possible and that is why the core
library exactly does what React is about, components. Routing, DOM rendering
and other logics are abstracted to a different library.
We need to install library by command to initialization router
1
|
$ user@administrator:/var/www/html/reactjs$ npm install react react-dom react-router –save
|
After Installing library we need to write following below code
to verify routing is working in desired manner.
1
2
3
4
5
6
|
File : main.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './RouterApp.jsx'
ReactDOM.render(<RouterApp
/>, document.getElementById('app'))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
File: RouterApp.jsx
import React, { Component } from
'react'
import { Router, Route, Link,
IndexRoute, hashHistory, browserHistory } from 'react-router'
class RouterApp extends Component
{
render() {
return (
<Router history={hashHistory}>
<Route path='/' component={Home} />
<Route path='/address' component={Address} />
<Route path='/country' component={Country}
/>
</Router>
)
}
}
const Home = () => <h1>Hello
from Home!, you can call "/address", "/country" to verify
routing</h1>
const Address = () => <h1>We
are located at 555 MG Street, Sector 15.</h1>
const Country = () => <h1>We
are located in India.</h1>
export default RouterApp
|
Q10:
What is Flux concept in ReactJS? Explain various flux elements including
Action, Dispatcher, Store and View. Give a simple practical example of
installing and using Flux in an application?
Flux is the architecture
of an application that Facebook uses for developing client-side web
applications. Facebook uses internally when working with React. It is not a framework or a library. This is simply a new
technique that complements React and the concept of Unidirectional Data Flow.
Facebook dispatcher
library is a sort of global pub/sub handler technique which
broadcasts payloads to registered callbacks.
Flux can be better explained by defining its individual
components:
§
Actions – They are helper
methods that facilitate passing data to the Dispatcher.
§
Dispatcher – It is Central hub
of app, it receives actions and broadcasts payloads to registered callbacks.
§
Stores – It is said to be
Containers for application state & logic that have callbacks registered to
the dispatcher. Every store maintains particular state and it will update
when it is needed. It wakes up on a relevant dispatch to retrieve the requested
data. It is accomplished by registering with the dispatcher when
constructed. They are similar to model in a traditional MVC (Model
View Controller), but they manage the state of many objects — it does not represent a single record of data like ORM models
do.
§
Controller Views –
React Components grabs the state from Stores and pass it down through
props to child components to view to render application.
In this Web Development
Tutorial, first we have to install all the steps mentioned in Question 2 i.e. step by step installation of react.
then, we need to install flux:
1
|
user@administrator:/var/www/html/reactjs$
npm install --save react-redux
|
Flux Overview – How it works?
Flux encourage the design in of a uni-directional data
flow.
All user interactions
within a view call an action creator,
which causes an action event to be emitted
from a singleton dispatcher.
The dispatcher is a
single-point-of-emission for all actions in a flux application. The action is
sent from the dispatcher to stores, which update
themselves in response to the action.
The flow doesn’t change
significantly for additional stores or views. The dispatcher simply sends every
action to all the stores in the
application.
Each store is responsible for a domain of the application, and
only update themselves in response to actions.
When a store updates, it emits a change event. In many React
applications, special views (known sometimes as “controller-views”) are
responsible for watching for this change event, reading the stores’ new data,
and passing that data through properties to child views.
It completely avoids performance issues , complex bugs that can
rise while trying to watch for specific property changes on models and
views only slightly.
No comments:
Post a Comment