React Quickstart Step Guide PDF
React Quickstart Step Guide PDF
Lionel Lopez
© Copyright 2017 by Lionel Lopez - All rights reserved.
If you would like to share this book with another person, please purchase an
additional copy for each recipient. Thank you for respecting the hard work of this
author. Otherwise, the transmission, duplication or reproduction of any of the
following work including specific information will be considered an illegal act
1. Introducing React
a. Introduction
b. History & Reason Of Popularity:
c. Reason of popularity:
d. What is State Management in React?
a. Installation
a.i. HTML Node JS
a.ii. Directory Explanation
4. Components in React
a. Components Introduction
b. What are components in React?
c. How to create a component?
d. Passing values to Components?
e. Function components:
f. Composing Components Multiple Times:
5. Styling in React
a. Installing Bootstrap
b. Radium
c. Useful option for styling in react
a. Installing SlimScroll
8. Transferring properties
a. Transferring Values
b. Transferring Functions
a. Installing Yii2
b. Installing React In Yii2
11. Going from Data to UI
12. The component lifecycle
a. Introduction
b. Installation
c. Using Route
d. Child Route
a. Jest Introduction
b. Getting Started
c. Small Test
d. Testing Components
a. Redux Introduction
b. Redux Three Principles
c. Installing Redux
d. Counter App In Redux React
This book is about React, A book written for React tutorial. React is based on
JavaScript. Let me tell you what is JavaScript? JavaScript is a web based
programming language and it was created by Brendan Eich, co-founder of Mozilla
project. Along with HTML and CSS, JavaScript is the core of World Wide Web and
it is one of the most popular languages of all time.
This book is for those who are looking for react book that teaches ReactJS from
beginning to advance level. This teaches you React basic and advanced concepts.
There are couple things you should know before learning ReactJS. Learning React
JS requires knowledge of Node JS and JavaScript, Here are more things you should
know, before diving into ReactJS:
Basic Knowledge Of HTMl, CSS and JavaScript
Important Programming Concepts
Dom Manipulation
Chapter 1
Introduction React
React is component based, In React, component can manage their own state to build
complex UI, for example If a user is logged in, then show logout link otherwise
show login form in same component. React also supports React Native to build
native apps in react, we can build IOS and Android apps in React Native that is
100% free. React can easily update view on data changes. React also provides
Routing, Routing includes Frontend Routing, in react routing is something is
different, Routing is based on components: React can be used to build very large
applications, which makes applications very fast and accurate. Here are some
reactions about React:
“The most fun UI lib I ever played with :) Compared to other approaches and libs
that tackle data binding and DOM events, this one was the easiest to understand and
become productive with."
“I am new to ReactJS and I can find ReactJS one of the easiest frameworks. I am a
blogger and I have choose react for blogging on my site, using Code Pen I can easy
put demos in my site. ”
React is created by gigantic Facebook. One of most used social networking website.
I prefer you to use React for future JavaScript applications because React is
supported by gigantic Facebook and other popular contributors.
React provides states features, States handles data for components, like input that
contains a string, Boolean that contains true or false, let's suppose you want to show
login form is user is not logged in and show logout button if user is logged in. This
can be handled by React JS states. We can easily change view according to state.
To make the long story short the designers at Facebook realized that JavaScript has
an enormous and I mean an immense biological community around it that is the
reason there are numerous libraries work around it despite the fact that it’s an
idiosyncratic dialect. React, Redux and Flux all have diverse standards or thoughts
behind them and engineers at Facebook ensured that they can work with React JS
Write HTML using JavaScript
HTML is extraordinary for static information, yet not all that good for
dynamic evolving information. Rather than utilizing a format dialect set up of
HTML, ReactJS route is to simply create HTML utilizing the JavaScript
dialect itself.
You can use the JSX compromise
You compose that "capacity" once and it'll generally mirror the present state.
We don't have to physically perform DOM operations to mirror the new state,
ReactJS will do that for us.
There is no MVC, you stream the application information through props to any
parts that need information. You can likewise stream callbacks for youngster’s
parts to get to specific activities of the application. Youngster’s parts can't
straightforwardly read or compose the application state. Composing parts with
very much characterized and obliged duties that don't meddle with others is the
thing that makes awesome React applications.
“NOTE: Remember I will use Node JS CLI in future chapters, because CLI is very
important rather than React in plain HTML. Every ReactJS project developers uses
Node JS to start React JS projects. So we will focus on learning Node JS based
React”.
React Itself:
https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/reactjsmin.js
React DOM:
https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js
Babel:
While including these libraries, Our Initial React Application should look like this:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<div id="root" ></div>
ReactDOM.render(
<div>
<HellWorld>Hello World</HellWorld>
</div>,
destination
);
</script>
</body>
</html>
If this code works successfully, our screen will be greeted with printed Hello World.
Second Way (CLI)
To install React using cli, we need Node JS to install, You can download NODE JS
here, After Node JS installs, go to CMD in windows or terminal in Mac/Ubuntu.
Type following command:
This will install create-react-app globally that will help us to create apps easily and
anywhere in our computer. Remember if you are a PHP developer, you don’t need to
put REACT JS applications in server like www folder of Xampp and htdocs of
Xampp. When this installation gets complete, we can install react using:
create-react-app my-app
cd my-app
npm start
This will create my-app directory and will install a complete react app setup. ReactJS
app will be available on http://localhost:3000, on new app, a message will be print
like this:
Directory Explanation
Public: Public folder contains public assets such as images, icons, files and other
important files that can be imported to app.
src: Src stands for source, this folder contains JavaScript source files or react app,
Which is built on JavaScript, It mean this folder contains JavaScript files.
Let’s create a hello world example in react cli app. Now delete all files in src folder,
make it empty. Now create two files in src folder,
● index.js
● HelloWorld.js
src/index.js
ReactDOM.render(
<HelloWorld/>,
document.getElementById('root')
)
src/HelloWorld.js
● React
● Principles of React
● Creating an App in React
In this chapter we have learned how to installed ReactJS and created hello world
example. Here is the exercise in the last:
src/HelloWorld.js
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './HelloWorld.js';
ReactDOM.render(
<HelloWorld/>,
document.getElementById('root')
)
We have ended our chapter and we have learned how to create an application. So
here are some questions:
What is create-react-app?
What is node_modules folder and why it is used for?
What is create-react-app?
This will install this cli command globally so we can install by:
npm install create-react-app
Components are Heart of React! Every react application has components. You can
say ReactJS is based on components. According to ReactJS definition:
“Components allows you to split the UI interface into small, reusable pieces.
Components are based on JavaScript functions. They accepts props, parameters or
we can say arguments and return React elements describing what should appear on
the screen. Components are heart of ReactJS, components build our ReactJS
application”.
According to book definition, the component allows us to split react app into small
pieces, like Navbar, Footer, Main Content, Cards, Images and etc. Component is
building part of application.
One thing more, every component must have a render function that renders a view,
For example, a footer component renders footer view and navbar component renders
navbar view and so on.
How to create a component?
Do you have ever think how to create components? How they look like? How to use
them? How to compose Components multiple times? Let’s learn all these things
now. Components in react can be created by React.Component keyword. Now create
a new HTML file:
Index.html
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<div id="root" ></div>
);
}
});
var HellWorld = React.createClass({
render: function() {
return (
<div>
<h1>{this.props.children}</h1>
</div>
);
}
});
ReactDOM.render(
<div>
<Navbar />
<HellWorld>Hello World</HellWorld>
</div>,
destination
);
</script>
</body>
</html>
Just like parameters we can also pass values to ReactJS components, and in React we
call them props, we can pass props by:
Just like attribute. Even we can pass functions as props. We have passed props in
NavBar, now we will use brandName in Navbar.js, so we can replace this code:
Into
You what does mean by a function, and you can see functional components in
heading, you might be worrying what functional components are? In ReactJS,
components can be composed by functions, we can pass parameter called props to
that functions we can use that props in our components according to our needs.
function Welcome(props) {
return (
<div>
<p>Hello World</p>
</div>
);
}
function Welcome(props) {
return (
<div>
<p>Hello World</p>
</div>
);
}
<Welcome />
function Button(props) {
return (
<button className={this.props.btnClass} >
{this.props.text}
</button>
);
}
<Button text='Click Me' btnClass='btn btn-info' />
This is nice technique to define components and in terms of using that components.
It is same. Whether a component is created by functional component or using
React.Component(). We can use that component by same technique by:
<ComponentName propName='Prop value, you can also pass function within props.'
/>
function Message(props) {
return (
<div>
{props.text}
</div>
);
}
ReactDOM.render(
<div>
<Message text='You got a message from John' />
<Message text='You got a message from Ali' />
<Message text='You got a message from Sarah' />
<Message text='You got a message from Janie' />
</div>
)
This will print Message component multiple times with different text. Even
components can be split into very smaller components, we can take this comment
example;
function Author(props) {
return (
<div>
<strong>{props.name}</strong>
</div>
);
}
function CommentText(props) {
return (
<div>
<p>
{props.comment}
</p>
</div>
);
}
function CommentActions(props) {
return (
<div>
<a>Edit</a>
<a>Like</a>
<a>Delete</a>
</div>
);
}
function Comment(props) {
return (
<div>
<Author name={props.author} />
<CommentText comment={props.comment} />
<CommentActions />
</div>
);
}
ReactDOM.render(
<div>
<Comment author='John' comment='Hello' />
<Comment author='Sarah' comment='How are you' />
</div>,
document.getElementById('root')
)
So, we have learned how to use components in our app, Again Components are
building blocks of our applications, Components can be split into very smaller
components. As we have done this task above. The component allows us to split
react app into small pieces, like Navbar, Footer, Main Content, Cards, Images
and etc. Component is building part of application.
Here is the exercise file for printing navbar and hello world
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<div id="root" ></div>
);
}
});
var HellWorld = React.createClass({
render: function() {
return (
<div>
<h1>{this.props.children}</h1>
</div>
);
}
});
ReactDOM.render(
<div>
<Navbar brandName="ReactJs" />
<HellWorld>Hello World</HellWorld>
</div>,
destination
);
</script>
</body>
</html>
Now we have completed Components chapter and here are some questions that you
have to answer.
Did you ever hear about Component? Component means a part or element of a larger
thing, component is a small part of a big thing. Now apply this to React JS.
Components are heart of ReactJS. Components are building part of your application.
Let’s suppose you have a navigation bar. We can call that navigation bar a
component. Everything in our ReactJS component.
I hope you know about functional component. Actually both are same things. There
is only one difference. Deceleration is different, but working and using is same.
As I’ve told you earlier, the component is the heart of ReactJS. The component is the
main feature in ReactJS. ReactJS apps are based on component and ReactJS is based
on only components.
Chapter 5
Styling in React
Take out last exercise file from chapter 3 navigation bar. This is what ReactJS is
looking right now:
This is not looking good without design. I've added bootstrap classes to navbar. So
we will add bootstrap to our project:
This will install bootstrap in ReactJS Now go and create a file with following content
and include bootstrap:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root" ></div>
);
}
});
var HellWorld = React.createClass({
render: function() {
return (
<div>
<h1>{this.props.children}</h1>
</div>
);
}
});
ReactDOM.render(
<div>
<Navbar brandName="ReactJs" />
<HellWorld>Hello World</HellWorld>
</div>,
destination
);
</script>
</body>
</html>
Now we have added bootstrap and as we have added bootstrap classes our React will
convert into bootstrap theme:
Now we have added bootstrap, and it is working without any problems. Now let's go
ahead and write some CSS, create a new style tag in your same HTML file and write
down below CSS file:
<style type="text/css">
.navbar {
background: green;
}
</style>
Do you have ever think how to style in React classes or you can how to style in
React component. Now let’s ahead and create a component called letter that prints
letters:
ReactDOM.render(
<div>
<Letter>R</Letter>
<Letter>e</Letter>
<Letter>a</Letter>
<Letter>c</Letter>
<Letter>t</Letter>
</div>,
destination
);
This will print letters of React, now go ahead and put each letter to styling, for this
we will use object styling in React. Creating an object that defines styling for a letter.
var letterStyle = {
height: 50,
width: 50,
background: this.props.bgColor,
display: 'inline-block',
fontSize: '25px',
textAlign: 'center'
};
Now use that object in each letter to style it!
Now we have provided style to letter and we let’s have final style:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
.navbar {
background: green;
}
</style>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
var Letter = React.createClass({
render: function() {
var letterStyle = {
height: 50,
width: 50,
background: this.props.bgColor,
display: 'inline-block',
fontSize: '25px',
textAlign: 'center'
};
return (
<span style={letterStyle} >{this.props.children}</span>
);
}
});
ReactDOM.render(
<div>
<Letter bgColor="red" >R</Letter>
<Letter bgColor="green" >e</Letter>
<Letter bgColor="blue" >a</Letter>
<Letter bgColor="pink" >c</Letter>
<Letter bgColor="purple">t</Letter>
</div>,
destination
);
</script>
</body>
</html>
Now copy this whole content and this will greet your app with:
background: this.props.bgColor,
As we have completed this chapter, here are some questions that I wanted to ask
from you:
This is comes to rescue when we need to update CSS when view changes. For
example, we need to set background blue on hover on circle. We can update our CSS
to blue when visitor hovers on a circle using events.
Is there any npm package for ReactJS Styling?
Yes there is a NPM package for ReactJS styling to increase ReactJS styling that
makes it easier to style on ReactJS. The name of package is react-styling. We can
install this package by:
Chapter conclusion
As we plunge further and take in more about React, you'll see a few more situations
where React does things very any other way than what we've been told is the right
method for getting things done on the web. In this instructional exercise, we saw
React advancing inline styles in JavaScript as an approach to style content rather
than utilizing CSS style rules. Prior, we took a gander at JSX and how the total of
your UI can be pronounced in JavaScript utilizing a XML-like linguistic structure
that looks like HTML.
In these cases, in the event that you look further underneath the surface, the
explanations behind why React veers from customary way of thinking bodes well.
Building applications with their exceptionally complex UI necessities requires
another method for comprehending them. HTML, CSS, and JavaScript procedures
that most likely appeared well and good when managing website pages and records
may not be pertinent in the web application world.
So, you should pick and pick the strategies that bode well for your circumstance.
While I am one-sided towards ReactJS method for taking care of our UI
improvement issues, I'll do my best to highlight substitute or traditional techniques
also. Binds that back to what we saw here, utilizing CSS style rules with your React
content is absolutely OK as long as you settled on the choice knowing the things you
pick up and additionally lose thusly.
Chapter 6
Building Complex Components
We have created very tiny application so far, in this chapter we will take a free
design from online and implement it in our react app. Again, let me explain again
what components are:
NOTE: “In this chapter we have used, NODE JS based react app to create a
example. You will need to go to installation part again understand again how to
install react using Node JS”. You can get Node JS here according to your system
architecture.
You can download this template here or you can use content from here because
every image, CSS file and JS file is free on this theme, so you download this theme
and use that content for free as I’ve did. from start bootstrap. On completion of this
chapter you will finally learn how to build complex components. Once you extract
the downloaded file, you will have following folder structure.
Following folder are not required, you can delete them.
● /less
● package.json
● Readme.md
● gulpfile.js
● license
● .gitignore
Now copy img/, js/ and lib/ folder to src folder, img/ folder should be on both src
folder/ and public/ folder, We will split html into components. Awesome right!
Now delete all old components and styles CSS files from src folder, now go and
review the theme we downloaded, you will following section, we can call them
components.
1. Navbar
2. Welcome Section
3. Download
4. Features
5. Call out
6. Social
7. Footer
● navbar/navbar.js
● welcome/welcome.js
● download/download.js
● features/features.js
● callout/callout.js
● social/social.js
● footer/footer.js
navbar/navbar.js
welcome/welcome.js
download/download.js
features/features.js
);
}
}
callout/callout.js
social/social.js
footer/footer.js
I’ve attached file destination for every component so you can find rest of the content
at given path.
Now import and use these component into index.js to build the theme.
src/index.js
</div>
);
}
ReactDOM.render(<Content />,document.getElementById('root'))
This should compile successfully and our app should look like this:
This is without CSS, as we have placed our CSS folder in src folder. Now import
following necessary files:
● Bootstrap Framework
● Font Awesome
● Theme CSS File
Now go ahead and create a CSS file called custom.css in src folder with following
content:
.navbar .navbar-brand {
color: #000 !important;
}
.navbar li a {
color: #000 !important;
}
.navbar {
background: white;
}
After importing all necessary files index.js file should look like this:
src/index.js
</div>
);
}
ReactDOM.render(<Content />,document.getElementById('root'))
So, we have built many components and successfully converted a theme into react,
following things we have learned in this chapter:
src/navbar/navbar.js
First Way:
Second Way:
Chapter conclusion:
As we have completed our chapter Components and we have learned how to create
ReactJS components. As told I earlier, components are building parts of our
application and they are heart of application. In next chapter we will learn how to
install jQuery plugins in our ReactJS applications.
Chapter 7
Installing and using jQuery Plugins in React
So, we have learned how to create components, how to create an app, styling in
ReactJS, in this chapter we will learn how to install jQuery plugins and using them.
So, let me tell you what is JQuery? JQuery is a JavaScript library, JQuery has dozens
of functions to deal with DOM, hiding them, removing them, and there are thousands
of plugins out there for JQuery. JQuery makes easier to make changes to DOM.
95% percent of plugins are free to install and using them on our website. JQuery
plugins can be easily embed to any web app.
In this chapter, we will learn how to install and use JQuery plugins in React app. To
run a JQuery plugin in react app, we will need jQuery in our application.
Go ahead and create a new fresh application. Remove all files from src folder keep
index.js and App.js with following content:
src/index.js
src/App.js
This will print Welcome to my App on the screen. Now let's go ahead and download
JQuery:
We will use JQuery SlimScroll by Rochal. Now create a file called slimscroll.js that
will convert body scrollbar into SlimScroll bar. As we have installed JQuery we can
import it and using jquery.getScript() function we can import a SlimScroll from a
CDN and run function after script.
src/slimscroll.js
Now we have learned how to use jQuery plugins in React Apps. Go ahead and try
another plugin. If you wondering how to add other plugins. The way is same as we
did in this demo. First you have to install jQuery and then use $.getScript() to require
script from a location. On $.getScript() callback, initialize your plugin as we did in
example.
JQuery is a JavaScript library. It is very fast, very small and feature rich. It makes
easy to play with DOM and its manipulation. Event handling, animation and Ajax
becomes easier with jQuery. JQuery is used to make web applications very fast and
that are easy to change.
$.ajax() is a Jquery function that allows us to create make Ajax calls. It is very easy
to use it with a Ajax. If you want to have Ajax feature in our ReactJS application.
Then I recommend to use $.ajax() with your ReactJS application. As we bind
component functions to component elements like button, input or form like click,
hover or submit. We can send ajax request on that function.
Chapter Conclusion:
Now we have completed this chapter and we have learned how to install jQuery
plugins. This chapter covers how to install jQuery plugins in our ReactJS App. Now
let’s move to chapter 8 and we will learn how to transfer data and functions between
components.
Chapter 8
Transferring data and functions through Components
We have learned how to create components and using them in our ReactJS
application. Did you’ve ever think how to pass parameters to components in React,
as you know we can data through functions like this;
functionName(value1,value2);
As you know we can call components by <MyComponent />, But how to pass data
to a component? We can pass data through functions as defined above. We can call
components in React like html tag, simply we can pass data through it by attributes:
In this chapter, we will learn again how to create components and pass values and
functions to it. In this chapter, let’s create a Button Component to show how to pass
data and functions to components in React, First install a fresh React plain
application.
index.html
ReactDOM.render(
<div>
<Button>Click me</Button>
</div>,
destination
);
This will print a button, this is a static button that will do nothing. As we have passed
child as button text, this is also type of props. Now go ahead add on click attribute to
button:
<button onClick={this.props.onClick} >{this.props.children}</button>
Now create a function and while calling button component. Pass that function to
button component
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
var Button = React.createClass({
render: function() {
return (
<button onClick={this.props.onClick} >{this.props.children}</button>
);
}
});
ReactDOM.render(
<div>
<Button onClick={buttonClick} >Click me</Button>
</div>,
destination
);
</script>
</body>
</html>
Let’s make something. Now we have learned how to pass functions and values to
components in React.
Quiz:
Go ahead and create to do app using React features learned so far. This can be
achieved by doing following things:
Creating a component that holds form and functions to store todo items.
A function that returns states.
All states
todoInput - contains input
todoLists - contains all todo lists.
Functions
updateInput - updates value to states right after a change is
made on input
save – this function stores new todo list, alerts a message
called “Please write something” if visito
Creating a component that lists all todo items.
Here is the app:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
var Todo = React.createClass({
getInitialState: function () {
return {
todoInput: "",
todoList: [],
}
},
updateInput: function (e) {
this.setState({todoInput: e.target.value});
},
: function (e) {
e.preventDefault();
if (this.state.todoInput) {
var oldTodos = this.state.todoList;
oldTodos.push([this.state.todoInput]);
this.setState({todoInput: ""});
}else {
alert("Please type something");
}
},
render: function() {
return (
<div>
<form onSubmit={this.save} >
<h3>Add a todo</h3>
<input className="form-control" value={this.state.todoInput}
onChange={this.updateInput} type="text" />
<br />
<button className="btn btn-info" >Save</button>
<hr />
<NumberList list={this.state.todoList} ></NumberList>
</form>
</div>
);
}
});
function NumberList(props) {
const list = props.list;
if (list.length == 0) {
var listItems = "No Items Right Now ";
}else {
var listItems = list.map((todoItem) =>
<li key={todoItem.toString()}>
<a>{todoItem}</a>
</li>
);
}
return (
<ul className="nav " >{listItems}</ul>
);
}
ReactDOM.render(
<div>
<Todo></Todo>
</div>,
destination
);
</script>
</body>
</html>
This will print todo app with bootstrap included. Let’s suppose a moment in which
we may have no todo lists and our app will render a message with no todo list:
After adding some items, ReactJS will render our items in following way:
Now we have working example of Todo List, Now take out the code from the
example and paste in a html file and open in your browser while including react,
react-dom and browser min js.
If you successfully paste this code, this file will greet you with a working example of
todo list.
Chapter conclusion:
Now we have successfully completed this chapter and we learned how to transfer
values and function using components props. Now let’s move to chapter Dealing
with states.
Chapter 9
Dealing with States
If you know working of properties, you will probably know how to work with states.
What is different between States and Properties?
States: We can store data in components by something well know states. We can
remove and update value of states, according to view changes.
onChange(e) {
this.setState({
todoInput: e.target.value
});
}
Let’s go ahead and create a fresh application, now go to src/app.js, To create new
state in constructor function:
constructor(props) {
super(props);
this.state = {
message: "Hello World"
};
}
For React.createClass()
getInitialState: function () {
return {
todoInput: "",
todoList: [],
}
},
I have assigned a state called message, All states comes in an object with values,
throughout component, all will be available on this.state, If we console.log state we
will have following result in console:
I have explained it already told you that states is an object that contains values. To
print this message, we can:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
Let’s create a button that will update the value of message and also create a that will
change value of message state.
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
render: function () {
return (
<div>
Welcome to Todo App | {this.state.message}
<br />
<button onClick={this.changeValue} >Click Me</button> to change
value
</div>
);
}
});
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
States comes with components, We can make our components dynamic using states
in ReactJS, in JavaScript,, state management is very big topic. We can change our
view using states. According to Wikipedia about state management it says:
Management of state of many interfaces that controls text fields, buttons, radio
inputs etc. In this user interface State Management is used to control other user
interfaces.
This explains very briefly about state management, changing view according to state
is called state management.
Another popular state management library, Redux is clearly the most popular of the
Flux implementations, an architecture championed by Facebook as a system for
managing state globally in React or other frontend libraries. 87% of users had heard
of Redux, which is pretty incredible given it is barely a year old and competing for
mindshare with a host of other Flux implementations (as we'll see below).
Redux is very popular state management software. For Vue js it Vuex. Redux is
created by software engineer at Facebook to control state management in ReactJS,,
later this tool become more popular to control state management in ReactJS, We
will learn Redux in future chapter. Specially served for Vue JS.
For both questions we have same answer that shows how to store components in
components and how to dynamically create components. It is a tricky to store
components and create components dynamically. This is how we can store
components in states and create components dynamically:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
This will help us to store components in store and create components dynamically.
Chapter 10
Integrating React With Yii 2
Let me tell you what Yii is, Yii is a superior PHP structure best to develop Web 2.0
applications. Yii accompanies rich elements: MVC, DAO/ActiveRecord,
I18N/L10N, reserving, verification and part based get to control, platform, testing,
and so forth. It can diminish your improvement time fundamentally. For this tutorial
we will need a web server to run PHP as well as Yii2, Current version of Yii is 2.00
version. Go ahead and download Yii2 from here. After downloading Yii2 project.
Extract the zip to a folder into www folder under Wamp or Xampp folder. Open the
extracted folder in and run init in cmd.
Write 1 and write y then hit enter. This will initialize Yii project for you. Now go to
http://localhost/path/to/yii2/frontend/web// to see if it works. If it works, Your screen
will be greeted with:
Now go to frontend/assets/AppAssets.php and add ReactJS:
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
/**
* Main frontend application asset bundle.
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
"https://fb.me/react-15.1.0.min.js",
"https://fb.me/react-dom-15.1.0.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js",
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
For JavaScript, we have now added ReactJS into our Yii project, and now go ahead
and do some coding. Create a folder in /frontend/web/js/react-components, Create
a folder in react-components called ReactJS that will import all react components.
We have include this file in frontend/layouts/main.php, after <?php $this-
>endBody() ?>
We have to use JSX platform to run make our Yii project compatible with ReactJS,
now go to console and see If there is a error and make sure your JavaScript added
files look alike this:
<script src="/react/yii/frontend/web/assets/922d48f2/jquery.js"></script>
<script src="/react/yii/frontend/web/assets/a08992ed/yii.js"></script>
<script src="https://fb.me/react-15.1.0.min.js"></script>
<script src="https://fb.me/react-dom-15.1.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
<script src="/react/yii/frontend/web/assets/1abd151d/js/bootstrap.js"></script>
<script type="text/jsx" src="js/react-components/reactjsjs" ></script>
ReactDOM.render(<HelloWorld />,document.getElementById('helloWorld'));
<?php
$this->title = 'My Yii Application';
?>
<div class="site-index">
<div id="helloWorld"></div>
</div>
It means we have successfully integrated react into our Yii project. Now we can use
all React resources in our Yii app. Now convert the navbar into React component.
Now go to frontend/web/js/reactjs and create a component for Navbar.Js
frontend/web/js/reactjsJs
ReactDOM.render(<Navbar />,document.getElementById('navbar'));
Now remove old navbar from frontend/layouts/main.php and add a div with id
navbar
Now we have integrated ReactJS into Yii project. Here are some questions:
What is Yii and why it is used for?
How to include Yii with Node JS based ReactJS Application?
Yii is used to develop PHP websites that are fast and scalable. Yii is popular due to
easy to learn, easy to understand and well manage framework.
Chapter Conclusion:
Now we have integrated ReactJS into Yii project. Now go ahead and write some
ReactJS code and make your Yii app full of ReactJS. Now go to let’s go to chapter
Going from data to UI.
Chapter 10
Going from Data to UI
This chapter is about using data to make UI, Making UI interactive by using data in
ReactJS Yeah! We can make our UI interactive by using data in ReactJS Let’s say
we have a circle in plain HTML and CSS,
.circle {
display: inline-block;
background: red;
height: 20px;
width: 20px;
border-radius: 50%;
text-align: center;
}
.circle.green {
background: green;
}
.circle.blue {
background: blue;
}
We will need different stylesheet to make circle background different. Like blue,
green etc. We will three div tags to make them different in color.
<div className="circle " ></div>
<div className="circle blue" ></div>
<div className="circle green" ></div>
Ok It worked! What if you will need 20 circle with different colors or 30 circles with
different circles. Are you going to write so much CSS? Ok, let's get rid of this
problem by components.
Go ahead and create a fresh react application, and create a component for circle,
create a file called circle.js
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
class App extends React.Component{
render() {
return (
<div>
<h3>Hello World</h3>
<Circle />
<Circle />
</div>
);
}
}
class Circle extends React.Component{
render() {
var circleStyles= {
display: 'inline-block',
background: 'red',
height: 20,
width: 20,
borderRadius: "50%",
textAlign: "center",
marginRight: '5'
}
return (
<div style={circleStyles} ></div>
);
}
}
var destination = document.querySelector("#root");
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
This compiles our circles, as I have said earlier we will need a feature that will
compiles our circle in different circles. Props save us from this problem.
Circle Component
App Component
This successfully created our circles, Instead of printing components like this:
Let's create an object before rendering and run for loop for colors. In every for loop.
Create component and assign a background color. Then use that variable in view.
App Component
Now if we don’t need to use component to add another circle to our app. We will to
push another color in our array:
App Component
This will print more circles. This explains how to use data to form UI in ReactJS we
have successfully created our circles.
This is our final exercise file, Now copy this file and if this works fine, you will be
greeted with circles on your screen!
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
Answer to question: I have asked question “How can you add a new circle on
button click?” You can create a function that adds a new circle, here is how you can
do it, create a constructor like this:
constructor(props) {
super(props);
this.state = {
myCircles: []
};
this.addCircle = this.addCircle.bind(this);
var colors = ['red','blue','yellow','pink','lightgreen',"lightblue","#eee","#42a"];
var circles = [];
for (var i = 0; i < colors.length; i++) {
var color = colors[i];
var c = <Circle key={i} bgColor={colors[i]} />;
circles.push(c);
}
this.state = {
myCircles: circles
};
}
That automatically adds circles to your web app. This will print same result as it did
before. Now add a button and create a function that adds a new circle to circles array
found instates
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<br />
<div class="container" >
<div id="root" ></div>
</div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
this.addCircle = this.addCircle.bind(this);
var colors =
['red','blue','yellow','pink','lightgreen',"lightblue","#eee","#42a"];
var circles = [];
for (var i = 0; i < colors.length; i++) {
var color = colors[i];
var c = <Circle key={i} bgColor={colors[i]} />;
circles.push(c);
}
this.state = {
myCircles: circles
};
}
render() {
return (
<div>
<h3>Hello World</h3>
{this.state.myCircles}
<br />
<br />
<button onClick={this.addCircle} >Add a circle</button>
</div>
);
}
addCircle() {
var circles = this.state.myCircles;
var newCircle = <Circle bgColor='blue' />;
circles.push(newCircle);
this.setState({myCircles: circles});
}
}
class Circle extends React.Component{
render() {
var circleStyles= {
display: 'inline-block',
background: this.props.bgColor,
height: 20,
width: 20,
borderRadius: "50%",
textAlign: "center",
marginRight: '5'
}
return (
<div style={circleStyles} ></div>
);
}
}
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
Now go ahead and you can see a button that adds a new circle on click
Here are some questions/quizzes:
When we apply new styles on hover state on an element. The transition does not
works. We will need to set a new transition style in CSS. Now set some transition on
class. Now set that transition on hover and focus state. Now write that CSS
deceleration on an element you want to apply transition.
Chapter Conclusion:
Now we have learned how to style in React. We have learned how to update our
style. We can update CSS when view changes. For example, we need to set
background blue on hover on circle. We can update our CSS to blue when visitor
hovers on a circle using events.
Chapter 12
The Component Lifecycle
Did you ever hear of events in JS? The component life cycle is based on events. We
can also say the component life events, When It will be rendered, After It mounts
and After It unmounts. React team created these events into methods. Here are
following Component lifecycle methods:
Let’s go ahead and create a fresh directory and create a component called
ComponentLifeCycle.js. I will put a on click increment example to it, so
conosle.log will show the events that are passing.
src/ComponentLifeCycle.js
import React from 'react';
constructor(props) {
super(props);
this.state = {
data: 0
}
this.setNewNumber = this.setNewNumber.bind(this)
};
setNewNumber() {
this.setState({data: this.state.data + 1})
}
render() {
return (
<div>
<button onClick = {this.setNewNumber}>INCREMENT</button>
<Content myNumber = {this.state.data}></Content>
</div>
);
}
}
componentWillMount() {
console.log('Component WILL MOUNT!')
}
componentDidMount() {
console.log('Component DID MOUNT!')
}
componentWillReceiveProps(newProps) {
console.log('Component WILL RECIEVE PROPS!')
}
shouldComponentUpdate(newProps, newState) {
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log('Component WILL UPDATE!');
}
componentDidUpdate(prevProps, prevState) {
console.log('Component DID UPDATE!')
}
componentWillUnmount() {
console.log('Component WILL UNMOUNT!')
}
render() {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
}
Now go to browser console and see logs, you will see something like this:
There are many functions in our component but only two functions execute, this is
because of events. Other events didn't pass. You can see a button on your app. Go
ahead and click on that button, you will see console full of logs.
Every Component has a few "lifecycle techniques" that you can abrogate to run code
at specific circumstances all the while. Strategies prefixed with will are called just
before something happens, and techniques prefixed with did are called directly in the
wake of something happens.
What is componentWillMount?
This method is executed before rendering on server side and client side. The React
expects this value as a function to be executed.
Chapter Conclusion:
So we have ended our chapter and we have learned how component life cycle works
now let’s turn to React Router
Chapter 13
React Router
In this chapter, we will learn building applications using react router. So first, what is
Router? A router is hardware device designed to receive, analyze and move
incoming packets to another network. In frontend, A router which navigates user to
different, every JavaScript framework or library has Router option.
● React Router
● Angular Router
● Vue Js Router
● Etc
This will install react router in our application and we can import react router by:
In this chapter, we will create a small app using React router. Navigation to different
URLs like:
1. /
2. /about
3. /contact
4. /login
5. /signup
The above will be our routers, The First one will be our home page, second page will
be about us page, third will be contact us page and Fourth and Fifth page will be
authentication pages.
Go ahead and create those components, remember in ReactJS the router is based on
components
App Component
</ReactRouter.Router>
</div>
);
}
}
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
Navbar Component
Home Component
About Component
Contact Component
Signup Component
Login Component
Now we have prepared all our components, and we have used bootstrap classes, so
don’t forget to add bootstrap in index.js
It seems our router is working, from navigation you can try to visit different parts of
applications. This is our whole React file:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root" ></div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="react_router.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
</ReactRouter.Router>
</div>
);
}
}
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
Now think in terms of URL parameters like user/1, user/2, lets build a Routing
system for users.
Users.js will list all users and user.js will show only one user who is selected. Now
add users and user to routes in app.js
We have added users and user to our route, Now add content to your user.js and
users.js
User Component
User Component
If we click one of the users, react router will take us to user view page.
Now we have got a working routing example. And this is our final exercise:
<!DOCTYPE html>
<html>
<head>
<title>React Hello World</title>
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root" ></div>
<script type="text/javascript" src="react.min.js" ></script>
<script type="text/javascript" src="react-dom.min.js" ></script>
<script type="text/javascript" src="react_router.js" ></script>
<script type="text/javascript" src="browser.min.js" ></script>
<script type="text/babel">
<li>
<a href="#/login" >Login</a>
</li>
<li>
<a href="#/signup" >Signup</a>
</li>
</ul>
</div>
</div>
</div>
);
}
}
ReactDOM.render(
<div>
<App></App>
</div>,
destination
);
</script>
</body>
</html>
Now go ahead and copy this file content and paste it in a html file and you will be
greeted with working example of React Routing.
Now chapter has been ended and I have a quiz from you. I hope you have better
understand what React Router is. Router redirects us to page when we clicked
on a link. How can you make this routing using JS code? Did you know about
it?
Chapter Conclusion:
● Introducing React
● Main principles of React
● Building your first react app
● Components in React
● Styling in React
● Creating complex components
● Use ReactJS components with another library
● Transferring properties
● Dealing with State
● Integrating React with Yii 2
● Going from Data to UI
● The component lifecycle
● Creating a single page app using react router
create-react-app my-app
Using comment create-react-app my-app, this command will create a new directory
and install our react app. This command gives directory listing:
my-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ └── favicon.ico
│ └── index.html
│ └── manifest.json
└── src
└── App.css
└── App.js
└── App.test.js
└── index.css
└── index.js
└── logo.svg
└── registerServiceWorker.js
● Package.json
This file contains info about installed
modules
● src/
This folder contains source code.
● public/
This folder contains asset files for our app.
● node_modules
This folder contains all installed modules
package.
● .gitignore
This file contains ignored files and folders
for github push and pull.
After installation gets complete. Go to installed directory and run your app
cd my-app
You can use yarn or NPM to run ReactJS app:
This command will initialize our app and if our application compiles successfully we
will be greeted with React welcome screen:
We have setup a environment setup in our application. Now let's create our app
build. We will need below command to build our app:
This will build our app in build folder. We will need to install serve globally to serve
our build app. You can install serve globally by:
This will install serve globally and we can serve our application by:
serve -s build
The same app will be run different server. But the application is ready to deploy!
As chapter has been ended and we have learned how to install Node JS based React
JS. Here is a question for you:
In case you didn’t know how to install application with Yarn. Go ahead to
https://yarnpkg.com/, and you can install yarn from here, you have follow following
conditions to install Node JS using yarn:
This will install create-react-app and let us to initialize our Node JS based React
Application.
Chapter Conclusion:
Now chapter has been ended and we have learned how to create Node JS based
ReactJS application. Now let’s move to chapter 15 where you will learn how to test
Application with JEST.
Chapter 15
Test your React application with Jest
Did you ever hear about Jest? Jest is a testing platform. Facebook uses Jest to test all
JavaScript code including their React applications. One of Jest's methods of insight
is to give a coordinated "zero-configuration" understanding. We watched that when
engineers are given prepared to-utilize instruments, they wind up composing more
tests, which thusly brings about more steady and sound code bases.
● Easy Setup
● Instant Feedback
● Snapshot Testing for debugging
Zero configuration
Jest is as of now arranged when you utilize make respond application or respond
local init to make your React and React Native activities. Place your tests in a
__tests__ envelope, or name your test records with a .spec.js or .test.jsextension.
Whatever you incline toward, Jest will discover and run your tests.
Jest works with any arrange to-JavaScript dialect and coordinates consistently with
Babel and with TypeScript through ts-jest.
Getting Started
Let's get started and install jest in our application and run a simple test, first we will
need to install jest in our application:
By Npm:
By Jest:
Both commands different but they install same jest in our react application.
Small Test
lets create a small test in our application, We can begin by composing a test for a
theoretical capacity that includes two numbers. Create a file named sum.test.js under
src/ directory. This will contain our actual test:
function sum(a, b) {
return a + b;
}
This will run a test to verify if a function returns 3 while adding numbers or by doing
something else like multiply, subtract and divide. Go ahead and add this line to
tests in package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
No go ahead and run npm t or npm test to run your test. If everything compiles
successfully, your CMD should look like this.
It means our app is successfully and our test is successfully passed. Now how to test
React application with Jest, let’s test our React application.
Testing Components
In this section, we will learn how to run test on React components. To run test on
React components we need to install Jest with babel. Because we are using Babel we
will install other modules that make Jest and Babel interact with each other:
This will install babel-jest, now create a file called .babelrc and put this content in it:
{
"presets": ["es2015", "react"]
}
So, we can import other components in our test file and we can easily test other
components. Now go ahead and create a file component.test.js that imports App
component and run test:
import App from './app.js';
});
If everything runs fine, this code will test App component and as there are no errors
in App component, So we will be greeted with PASS on CMD.
This means we have successfully tested our React Applications and it works fine and
let's go ahead run ReactJS app with
npm start
This will start application server on http://localhost:3000, and we will greeted with
app without errors.
In case you did not know what JEST is? Jest is delightful JavaScript testing. Jest has
following features:
Easy Setup.
Instant Feedback.
Snapshot testing.
Zero Configuration Testing.
Fast.
Reports.
Power mocking library.
Works with typescript.
Chapter Conclusion
So now we have completed chapter 15 and we have learn how to install JEST and
test your applications in it. Now go ahead to chapter 16 for Redux.
Chapter 16
Charge your React application with Redux
Do you have heard about Redux? Redux is a predictable state container for
JavaScript apps.
Redux is created by Dan Abramov, Who works at Facebook. Redux is not for
ReactJS, Redux is for the whole JavaScript. Redux is inspired by Facebook’s Flux
and influenced by functional programming language Elm.
Three Principles of Redux
The state of our whole application is stored in one object. Our whole
application is depend on only one object. Which makes easier to understand
and make changes to our states. We can call it single tree. A single state tree
also makes it easier to debug or inspect an app.
console.log(store.getState())
/* Prints
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
*/
store.dispatch({
type: 'COMPLETE_TODO',
index: 1
})
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})
Pure functions are those functions which returns expected result based on the
parameters. They’re purely synchronous not asynchronous. To make changes
in our store we use these functions and we call them reducers. They don’t
mutate existing state rather they create a new state tree.
This will Redux in our React application. Do you have ever think why we would
need Redux in our application? Let's say we have a component called Main
Component. And Main Component have child Components. If main component has
to deliver states to its child components. They to make a relationship tree that will
delivery states. But If there are lots of components and they have a lot of child
components. What you should do? Store rescue us from this problem. That
distributes states between components.
This is all about Redux! Now let’s go ahead and install Redux in our React
application.
src/index.js
This will import createStore from Redux. Then we can create a new reducer also
called functions:
const Reducer = (state, action) => {
switch (action.type) {
case 'ADD':
state = state + action.payload;
break;
case 'SUBTRACT':
state = state - action.payload;
break;
}
return state;
}
That Adds and Subtracts numbers. Then we will create a new store.
We created a store with initial value 0 for state to subtract and add. Then we can
create a callback function that will run when a state is changed!
store.subscribe(() => {
console.log("Store Updated!",store.getState());
});
store.dispatch({
type: "ADD",
payload: 3
});
store.dispatch({
type: "ADD",
payload: 1
});
store.subscribe(() => {
console.log("Store Updated!",store.getState());
});
store.dispatch({
type: "ADD",
payload: 3
});
store.dispatch({
type: "ADD",
payload: 1
});
store.dispatch({
type: "ADD",
payload: 2
});
ReactDOM.render(<App />,document.getElementById('root'));
Now go to your web console and see this will print on your console:
This means our Redux application is working! Right. so Create we can create
another example, A working example. We will create a button click increment
example. If a user clicks on a button, the counter will increment the times the button
is clicked. let’s create a folder called components and reducers under /src directory.
src/components/Counter.js
import React, { Component } from 'react'
import PropTypes from 'prop-types'
incrementIfOdd() {
if (this.props.value % 2 !== 0) {
this.props.onIncrement()
}
}
incrementAsync() {
setTimeout(this.props.onIncrement, 1000)
}
render() {
const { value, onIncrement, onDecrement } = this.props
return (
<p>
Clicked: {value} times
{' '}
<button onClick={onIncrement}>
+
</button>
{' '}
<button onClick={onDecrement}>
-
</button>
{' '}
<button onClick={this.incrementIfOdd}>
Increment if odd
</button>
{' '}
<button onClick={this.incrementAsync}>
Increment async
</button>
</p>
)
}
}
Counter.propTypes = {
value: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired
}
src/reducers/index.js
src/index.js
render()
store.subscribe(render)
In any case, to start with, I ought to likely bring up that Flux is an example and
Redux is a library. Flux is a favor name for the eyewitness design altered a tiny bit to
fit React.
Both Flux and Redux have activities. Activities can be contrasted with occasions (or
what trigger occasions). In Flux, an activity is a straightforward JavaScript question,
and that is the default case in Redux as well, yet when utilizing Redux middleware,
activities can likewise be capacities and guarantees.
With Flux it is a tradition to have numerous stores per application; each store is a
singleton protest. In Redux, the tradition is to have a solitary store for every
application, normally isolated into information spaces inside (you can make more
than one Redux store if necessary for more mind boggling situations).
Flux has a solitary dispatcher and all activities need to go through that dispatcher. It's
a singleton question. A Flux application can't have numerous dispatchers. This is
required in light of the fact that a Flux application can have different stores and the
conditions between those stores require a solitary chief, which is the dispatcher.
Redux has no dispatcher element. Rather, the store has the dispatching procedure
heated in. A Redux store uncovered a couple of straightforward API capacities, one
of them is to dispatch activities.
In Flux, the rationale of what to do on the information in view of the got activity is
composed in the store itself. The store additionally has the adaptability of what parts
of the information to uncover freely. The most brilliant player in a Flux application
is the store.
In Redux, the rationale of what to do on the information in light of the got activities
is in the reducer work that gets required each activity that gets dispatched (through
the store API). A store can't be characterized without a reducer work. A Redux
reducer is a straightforward capacity that gets the past state and one activity, and it
restores the new state in view of that activity. In a Redux application, you can part
your reducer into less difficult capacities as you would do with whatever other
capacity. The most brilliant player in Redux is the reducer.
In Redux, likewise, there isn't a ton of adaptability about what to uncover as the
store's state. Redux will simply uncover whatever came back from the store's
reducer. This is one requirement.
The other greater requirement is that the store's state can't be variable (or truly,
shouldn't be). There is no such limitation in Flux, you can change the state as you
wish. The state's changelessness, in Redux, is accomplished effortlessly by making
the reducers immaculate capacities (with no reactions). Reducers dependably
duplicate the state they get and restores an altered variant of the state's duplicate, not
simply the first question. While this is a major limitation, it makes life significantly
less demanding long haul.
We have learned how to build a react app and compiling it for production version. In
this chapter, we will discuss about ReactJS Here are some questions that we will
focus on this chapter:
React is exceptionally a basic and lightweight library that lone manages the view
layer. It is not a mammoth like other MV* structures, for example, Angular or
Ember. Any JavaScript engineer can comprehend the essentials and begin building
up an amazing web application after just several days perusing instructional exercise.
As the React direct says 'Thinking in React' might be somewhat not quite the
same as you used to since it conveys another way to deal with the table, yet it
will turn out to be considerably less demanding and regular as you pick up
involvement with it.
2. Reusable Components:
React gives a component based structure. Components are your Lego pieces.
You begin with modest parts like a catch, check box, drop-down and so forth
and you make wrapper segments made out of those littler segments. And
afterward, you compose larger amount wrapper segments. Furthermore, it
goes on like that until the point when you have this one root part and that
segment is your application.
Developer toolset is another essential factor when you are picking a development
platform. There are two awesome tools you ought to know about: React Developer
Tools and Redux Developer Tools. Both can be introduced as Chrome expansions.
4. React Native
Learning React accompanies a reward: React Native. React is not a 'compose once
run anyplace library', as the makers say, it's a 'learn once compose anyplace' library.
Yes, you can compose local applications for Android and IOS utilizing React Native.
In spite of the fact that you won't have the capacity to utilize precisely the same you
composed for web, you will have the capacity to utilize a similar philosophy and a
similar engineering.
<App>
<AppNavbar>
<AppNavbarBrand></AppNavbarBrand>
<AppNavbarBrandLinks></AppNavbarBrandLinks>
</AppNavbar>
<Grid padding='0' >
<Half>
<ChatSidebar></ChatSidebar>
</Half>
<Half>
<ChatContent></ChatContent>
</Half>
</Grid>
<Footer></Footer>
</App>
This is just imagination for chat application. It shows to how to create components.
Again! Create a directory for these components:
● src/components/
/chat
■ ChatSidebar.js
■ ChatContent.js
● src/components/grid
Grid
Half
● Footer
Footer.js
Larger apps may have hundreds of components. This is very simplified component
structure.
There are bunch of CSS frameworks and libraries you can use in your react app.
Here are some popular CSS libraries you can use in React app:
● Bootstrap
Bootstrap, a sleek, intuitive, and powerful mobile first front-end framework for faster
and easier web development. Bootstrap is written in SASS.
● Bulma
Bulma is an open source CSS framework based on Flex box and built with Sass. It's
100% responsive, fully modular, and available for free.
● Semantic UI
Semantic UI is probably one of most used CSS library of all time. Semantic UI is
easy to implement in any project and we can easily embed plugin which we are using
in our app. Semantic UI can be easily embed to React app. We can just simply use
● Foundation
In this book we have learned about ReactJS React Components, React Router, How
to run jQuery plugins in our React apps, Dealing with States, Building Complex
components, Creating Single Page Apps using react router, Testing React with Jest,
Charging our application with Redux.
Best of luck!