React Js Tutorial
React Js Tutorial
ReactJS
Audience
This tutorial will help JavaScript developers who look ahead to deal with ReactJS for the
first time. We will try to introduce every concept by showing simple code examples that
can be easily understood. After finishing all the chapters, you will feel confident working
with ReactJS. As a bonus we will introduce additional elements that work well with ReactJS
to help you learn the best practices and follow the modern JavaScript trends.
Prerequisites
If you want to work with ReactJS, you need to have solid knowledge of JavaScript,
HTML5, and CSS. Even though ReactJS doesn't use HTML, the JSX is similar so your HTML
knowledge will be very helpful. We will explain this more in one of the next chapters. We
will also use EcmaScript 2015 syntax so any knowledge in this area can be helpful.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
ReactJS
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
Attributes ................................................................................................................................................ 9
Styling ................................................................................................................................................... 11
Comments ............................................................................................................................................. 12
Naming Convention............................................................................................................................... 13
ii
ReactJS
Force Update......................................................................................................................................... 30
Child Events........................................................................................................................................... 42
iii
ReactJS
Step 4 - Reducers................................................................................................................................... 55
Step 5 - Store......................................................................................................................................... 56
iv
ReactJS
1. ReactJS ─ Overview
ReactJS is JavaScript library used for building reusable UI components. According to React
official documentation, following is the definition −
React is a library for building composable user interfaces. It encourages the creation of
reusable UI components, which present data that changes over time. Lots of people use
React as the V in MVC. React abstracts away the DOM from you, offering a simpler
programming model and better performance. React can also render on the server using
Node, and it can power native apps using React Native. React implements one-way
reactive data flow, which reduces the boilerplate and is easier to reason about than
traditional data binding.
React ─ Features
JSX − JSX is JavaScript syntax extension. It isn't necessary to use JSX in React
development, but it is recommended.
Unidirectional data flow and Flux − React implements one-way data flow which
makes it easy to reason about your app. Flux is a pattern that helps keeping your
data unidirectional.
React ─ Advantages
Uses virtual DOM which is a JavaScript object. This will improve apps performance,
since JavaScript virtual DOM is faster than the regular DOM.
Can be used on client and server side as well as with other frameworks.
Component and data patterns improve readability, which helps to maintain larger
apps.
React ─ Limitations
Covers only the view layer of the app, hence you still need to choose other
technologies to get a complete tooling set for development.
Uses inline templating and JSX, which might seem awkward to some developers.
1
ReactJS
2. ReactJS ─ Environment Setup
In this chapter, we will show you how to set up an environment for successful React
development. Notice that there are many steps involved but this will help speed up the
development process later. We will need NodeJS, so if you don't have it installed, check
the link from the following table.
Sr.
Software Description
No.
C:\Users\username\Desktop>mkdir reactApp
C:\Users\username\Desktop\reactApp>npm init
Since we want to use React, we need to install it first. The --save command will add these
packages to package.json file.
2
ReactJS
As already mentioned, we will need some babel plugins, so let's install it too.
C:\Users\username\Desktop\reactApp>touch index.html
C:\Users\username\Desktop\reactApp>touch App.jsx
C:\Users\username\Desktop\reactApp>touch main.js
C:\Users\username\Desktop\reactApp>touch webpack.config.js
And lastly, we are setting babel loaders to search for js files, and use es2015 and react
presets that we installed before.
webpack.config.js
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
3
ReactJS
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
Open the package.json and delete "test" "echo \"Error: no test specified\" && exit
1" inside "scripts" object. We are deleting this line since we will not do any testing in this
tutorial. Let's add the start command instead.
Now, we can use npm start command to start the server. --hot command will add live
reload after something is changed inside our files so we don't need to refresh the browser
every time we change our code.
Step 6 - index.html
This is just regular HTML. We are setting div id = "app" as a root element for our app
and adding index.js script, which is our bundled app file.
<!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>
4
ReactJS
</body>
</html>
App.jsx
import React from 'react';
We need to import this component and render it to our root App element, so we can see
it in the browser.
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
Note: Whenever you want to use something, you need to import it first. If you want to
make the component usable in other parts of the app, you need to export it after creation
and import it in the file where you want to use it.
5
ReactJS
C:\Users\username\Desktop\reactApp>npm start
It will show the port we need to open in the browser. In our case, it is
http://localhost:8080/. After we open it, we will see the following output.
6
ReactJS
3. ReactJS ─ JSX
React uses JSX for templating instead of regular JavaScript. It is not necessary to use it,
however, following are some pros that come with it.
It is also type-safe and most of the errors can be caught during compilation.
It makes it easier and faster to write templates, if you are familiar with HTML.
Using JSX
JSX looks like a regular HTML in most cases. We already used it in the Environment Setup
chapter. Look at the code from App.jsx where we are returning div.
App.jsx
import React from 'react';
Even though it's similar to HTML, there are a couple of things we need to keep in mind
when working with JSX.
7
ReactJS
Nested Elements
If we want to return more elements, we need to wrap it with one container element.
Notice, how we are using div as a wrapper for h1, h2 and p elements.
App.jsx
import React from 'react';
8
ReactJS
Attributes
We can use our own custom attributes in addition to regular HTML properties and
attributes. When we want to add custom attribute, we need to use data- prefix. In the
following example, we added data-myattribute as an attribute of p element.
JavaScript Expressions
JavaScript expressions can be used inside of JSX. We just need to wrap it with curly
brackets {}. The following example will render 2.
9
ReactJS
We cannot use if else statements inside JSX, instead we can use conditional
(ternary) expressions. In the following example, variable i equals to 1, so the browser
will render true. If we change it to some other value, it will render false.
var i = 1;
return (
<div>
<h1>{i == 1 ? 'True!' : 'False'}</h1>
</div>
);
}
}
10
ReactJS
Styling
React recommends using inline styles. When we want to set inline styles, we need to
use camelCase syntax. React will also automatically append px after the number value
on specific elements. The following example shows how to add myStyle inline
to h1 element.
var myStyle = {
fontSize: 100,
color: '#FF0000'
}
return (
<div>
<h1 style = {myStyle}>Header</h1>
</div>
);
}
}
export default App;
11
ReactJS
Comments
When writing comments, we need to put curly brackets {} when we want to write
comment within children section of a tag. It is a good practice to always use {} when
writing comments, since we want to be consistent when writing the app.
12
ReactJS
Naming Convention
HTML tags always use lowercase tag names, while React components start with
Uppercase.
Note: You should use className and htmlFor as XML attribute names instead
of class and for.
Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute
names. Instead, React DOM components expect DOM property names such as
className and htmlFor, respectively.
13
ReactJS
4. ReactJS ─ Components
In this chapter, we will learn how to combine components to make the app easier to
maintain. This approach allows to update and change your components without affecting
the rest of the page.
Stateless Example
Our first component in the following example is App. This component is owner of Header
and Content. We are creating Header and Content separately and just adding it inside
JSX tree in our App component. Only App component needs to be exported.
App.jsx
import React from 'react';
14
ReactJS
<h2>Content</h2>
<p>The content text!!!</p>
</div>
);
}
}
To be able to render this on the page, we need to import it in main.js file and call
reactDOM.render(). We already did this while setting the environment.
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
15
ReactJS
Stateful Example
In this example, we will set the state for owner component (App). The Header component
is just added like in the last example since it doesn't need any state. Instead of content
tag, we are creating table and tbody elements, where we will dynamically insert
TableRow for every object from the data array.
It can be seen that we are using EcmaScript 2015 arrow syntax (⇒) which looks much
cleaner than the old JavaScript syntax. This will help us create our elements with fewer
lines of code. It is especially useful when we need to create a list with a lot of items.
App.jsx
import React from 'react';
this.state = {
data:
[
{
"id":1,
"name":"Foo",
"age":"20"
},
{
"id":2,
"name":"Bar",
"age":"30"
},
{
"id":3,
"name":"Baz",
"age":"40"
}
]
16
ReactJS
}
}
render() {
return (
<div>
<Header/>
<table>
<tbody>
{this.state.data.map((person, i) => <TableRow key = {i} data
= {person} />)}
</tbody>
</table>
</div>
);
}
}
17
ReactJS
);
}
}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Note: Notice that we are using key = {i} inside map() function. This will help React to
update only the necessary elements instead of re-rendering the entire list when something
changes. It is a huge performance boost for larger number of dynamically created
elements.
18
ReactJS
5. ReactJS ─ State
State is the place where the data comes from. We should always try to make our state as
simple as possible and minimize the number of stateful components. If we have, 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.
Using Props
The following sample code shows how to create a stateful component using
EcmaScript2016 syntax.
App.jsx
import React from 'react';
this.state = {
header: "Header from state...",
"content": "Content from state..."
}
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<h2>{this.state.content}</h2>
</div>
);
}
}
19
ReactJS
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
20
ReactJS
6. ReactJS ─ Props Overview
The main difference between state and props is that props are immutable. This is why the
container component should define the state that can be updated and changed, while the
child components should only pass data from the state using props.
Using Props
When we need immutable data in our component, we can just add props to
reactDOM.render() function in main.js and use it inside our component.
App.jsx
import React from 'react';
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
21
ReactJS
Default Props
You can also set default property values directly on the component constructor instead of
adding it to the reactDom.render() element.
App.jsx
import React from 'react';
22
ReactJS
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
App.jsx
import React from 'react';
this.state = {
header: "Header from props...",
23
ReactJS
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
24
ReactJS
ReactDOM.render(<App/>, document.getElementById('app'));
The result will again be the same as in the previous two examples, the only thing that is
different is the source of our data, which is now originally coming from the state. When
we want to update it, we just need to update the state, and all child components will be
updated. More on this in the Events chapter.
25
ReactJS
7. ReactJS ─ Props Validation
Properties validation is a useful way to force the correct usage of the components. This
will help during development to avoid future bugs and problems, once the app becomes
larger. It also makes the code more readable, since we can see how each component
should be used.
Validating Props
In this example, we are creating App component with all the props that we need.
App.propTypes is used for props validation. If some of the props aren't using the correct
type that we assigned, we will get a console warning. After we specify validation patterns,
we will set App.defaultProps.
App.jsx
import React from 'react';
App.propTypes = {
propArray: React.PropTypes.array.isRequired,
propBool: React.PropTypes.bool.isRequired,
propFunc: React.PropTypes.func,
26
ReactJS
propNumber: React.PropTypes.number,
propString: React.PropTypes.string,
propObject: React.PropTypes.object
}
App.defaultProps = {
propArray: [1,2,3,4,5],
propBool: true,
propFunc: function(e){return e},
propNumber: 1,
propString: "String value...",
propObject: {
objectName1:"objectValue1",
objectName2: "objectValue2",
objectName3: "objectValue3"
}
}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
27
ReactJS
Since all props are valid, we will get the following result.
As can be noticed, we have use isRequired when validating propArray and propBool.
This will give us an error, if one of those two don't exist. If we delete propArray:
[1,2,3,4,5] from the App.defaultProps object, the console will log a warning.
If we set the value of propArray: 1, React will warn us that the propType validation has
failed, since we need an array and we got a number.
28
ReactJS
8. ReactJS ─ Component API
In this chapter, we will explain React component API. We will discuss three methods:
setState(), forceUpdate and ReactDOM.findDOMNode(). In new ES6 classes, we
have to manually bind this. We will use this.method.bind(this) in the examples.
Set State
setState() method is used to update the state of the component. This method will not
replace the state, but only add changes to the original state.
29
ReactJS
We started with an empty array. Every time we click the button, the state will be updated.
If we click five times, we will get the following output.
Force Update
Sometimes we might want to update the component manually. This can be achieved using
the forceUpdate() method.
30
ReactJS
We are setting a random number that will be updated every time the button is clicked.
31
ReactJS
<div id = "myDiv">NODE</div>
</div>
);
}
}
export default App;
The color of myDiv element changes to green, once the button is clicked.
Note: Since the 0.14 update, most of the older component API methods are deprecated
or removed to accommodate ES6.
32
ReactJS
9. ReactJS ─ Component Life Cycle
Lifecycle Methods
componentWillMount is executed before rendering, on both the server and the
client side.
componentDidMount is executed after the first render only on the client side.
This is where AJAX requests and DOM or state updates should occur. This method
is also used for integration with other JavaScript frameworks and any functions
with delayed execution such as setTimeoutor setInterval. We are using it to
update the state, so we can trigger the other lifecycle methods.
In the following example, we will set the initial state in the constructor function.
The setNewnumber is used to update the state. All the lifecycle methods are inside
the Content component.
App.jsx
import React from 'react';
33
ReactJS
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>
);
}
}
class Content extends React.Component {
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!')
34
ReactJS
}
render() {
return (
<div>
<h3>{this.props.myNumber}</h3>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
setTimeout(() => {
ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 10000);
35
ReactJS
When we click the INCREMENT button, the update will occur and other lifecycle methods
will be triggered.
After ten seconds, the component will unmount and the last event will be logged in the
console.
Note: Lifecycle methods will always be invoked in the same order so it is a good practice
to write it in the correct order as shown in the example.
36
ReactJS
10. ReactJS ─ Forms
Simple Example
In the following example, we will set an input form with value = {this.state.data}. This
allows to update the state whenever the input value changes. We are using onChange
event that will watch the input changes and update the state accordingly.
App.jsx
import React from 'react';
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div>
<input type = "text" value = {this.state.data}
onChange = {this.updateState} />
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
37
ReactJS
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
When the input text value changes, the state will be updated.
Complex Example
In the following example, we will see how to use forms from child component. onChange
method will trigger state update that will be passed to the child input value and rendered
on the screen. A similar example is used in the Events chapter. Whenever we need to
update state from child component, we need to pass the function that will handle updating
(updateState) as a prop (updateStateProp).
App.jsx
import React from 'react';
this.state = {
data: 'Initial data...'
}
38
ReactJS
this.updateState = this.updateState.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
render() {
return (
<div>
<Content myDataProp = {this.state.data}
updateStateProp = {this.updateState}></Content>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<input type = "text" value = {this.props.myDataProp}
onChange = {this.props.updateStateProp} />
<h3>{this.props.myDataProp}</h3>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
39
ReactJS
40
ReactJS
11. ReactJS ─ Events
Simple Example
This is a simple example where we will only use one component. We are just
adding onClick event that will trigger updateState function once the button is clicked.
App.jsx
import React from 'react';
this.state = {
data: 'Initial data...'
}
this.updateState = this.updateState.bind(this);
};
updateState() {
this.setState({data: 'Data updated...'})
}
render() {
return (
<div>
<button onClick = {this.updateState}>CLICK</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
41
ReactJS
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Child Events
When we need to update the state of the parent component from its child, we can create
an event handler (updateState) in the parent component and pass it as a prop
(updateStateProp) to the child component where we can just call it.
App.jsx
import React from 'react';
42
ReactJS
};
updateState() {
this.setState({data: 'Data updated from the child component...'})
}
render() {
return (
<div>
<Content myDataProp = {this.state.data}
updateStateProp = {this.updateState}></Content>
</div>
);
}
}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
43
ReactJS
44
ReactJS
12. ReactJS ─ Refs
The ref is used to return a reference to the element. Refs should be avoided in most
cases, however, they can be useful when we need DOM measurements or to add methods
to the components.
Using Refs
The following example shows how to use refs to clear the input field. ClearInput function
searches for element with ref = "myInput" value, resets the state, and adds focus to it
after the button is clicked.
App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
this.state = {
data: ''
}
this.updateState = this.updateState.bind(this);
this.clearInput = this.clearInput.bind(this);
};
updateState(e) {
this.setState({data: e.target.value});
}
clearInput() {
this.setState({data: ''});
ReactDOM.findDOMNode(this.refs.myInput).focus();
}
render() {
return (
<div>
<input value = {this.state.data} onChange = {this.updateState}
45
ReactJS
ref = "myInput"></input>
<button onClick = {this.clearInput}>CLEAR</button>
<h4>{this.state.data}</h4>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
Once the button is clicked, the input will be cleared and focused.
46
ReactJS
13. ReactJS ─ Keys
React keys are useful when working with dynamically created components or when your
lists are altered by the users. Setting the key value will keep your components uniquely
identified after the change.
Using Keys
Let's dynamically create Content elements with unique index (i). The map function will
create three elements from our data array. Since the key value needs to be unique for
every element, we will assign i as a key for each created element.
App.jsx
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
{
component: 'First...',
id: 1
},
{
component: 'Second...',
id: 2
},
{
component: 'Third...',
id: 3
}
]
}
}
47
ReactJS
render() {
return (
<div>
<div>
{this.state.data.map((dynamicComponent, i) => <Content
key = {i} componentData = {dynamicComponent}/>)}
</div>
</div>
);
}
}
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App/>, document.getElementById('app'));
48
ReactJS
We will get the following result for the Key values of each element.
If we add or remove some elements in the future or change the order of the dynamically
created elements, React will use the key values to keep track of each element.
49
ReactJS
14. ReactJS ─ Router
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
{this.props.children}
</div>
)
}
}
50
ReactJS
51
ReactJS
main.js
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
When the app is started, we will see three clickable links that can be used to change the
route.
52
ReactJS
15. ReactJS ─ Flux Concept
Flux is a programming concept, where the data is uni-directional. This data enters the
app and flows through it in one direction until it is rendered on the screen.
Flux Elements
Following is a simple explanation of the flux concept. In the next chapter, we will learn
how to implement this into the app.
Actions − Actions are sent to the dispatcher to trigger the data flow.
Dispatcher − This is a central hub of the app. All the data is dispatched and sent
to the stores.
Store − Store is the place where the application state and logic are held. Every
store is maintaining a particular state and it will update when needed.
View − The view will receive data from the store and re-render the app.
Flux Pros
Single directional data flow is easy to understand.
The app is easier to maintain.
The app parts are decoupled.
53
ReactJS
16. ReactJS ─ Using Flux
In this chapter, we will learn how to implement flux pattern in React applications. We will
use Redux framework. The goal of this chapter is to present the simplest example of every
piece needed for connecting Redux and React.
Step 3 - Actions
Actions are JavaScript objects that use type property to inform about the data that should
be sent to the store. We are defining ADD_TODO action that will be used for adding new
item to our list. The addTodo function is an action creator that returns our action and sets
an id for every created item.
actions/actions.js
export const ADD_TODO = 'ADD_TODO'
let nextTodoId = 0;
export function addTodo(text) {
return {
54
ReactJS
type: ADD_TODO,
id: nextTodoId++,
text
};
}
Step 4 - Reducers
While actions only trigger changes in the app, the reducers specify those changes. We
are using switch statement to search for a ADD_TODO action. The reducer is a function
that takes two parameters (state and action) to calculate and return an updated state.
The first function will be used to create a new item, while the second one will push that
item to the list. Towards the end, we are using combineReducers helper function where
we can add any new reducers we might use in the future.
reducers/reducers.js
import { combineReducers } from 'redux'
import { ADD_TODO } from '../actions/actions'
case ADD_TODO:
return {
id: action.id,
text: action.text,
}
default:
return state
}
}
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
todo(undefined, action)
55
ReactJS
]
default:
return state
}
}
const todoApp = combineReducers({
todos
})
export default todoApp
Step 5 - Store
The store is a place that holds the app's state. It is very easy to create a store once you
have reducers. We are passing store property to the provider element, which wraps our
route component.
main.js
import React from 'react'
render(
<Provider store = {store}>
<App />
</Provider>,
rootElement
)
56
ReactJS
This function takes select function as an argument. Select function takes the state from
the store and returns the props (visibleTodos) that we can use in our components.
App.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addTodo } from './actions/actions'
return (
<div>
<AddTodo
onAddClick = {text ⇒
dispatch(addTodo(text))}
/>
<TodoList todos = {visibleTodos}/>
</div>
)
}
}
function select(state) {
return {
visibleTodos: state.todos
}
}
export default connect(select)(App)
57
ReactJS
components/AddTodo.js
import React, { Component, PropTypes } from 'react'
export default class AddTodo extends Component {
render() {
return (
<div>
<input type = 'text' ref = 'input' />
<button onClick = {(e) ⇒ this.handleClick(e)}>
Add
</button>
</div>
)
}
handleClick(e) {
const node = this.refs.input
const text = node.value.trim()
this.props.onAddClick(text)
node.value = ''
}
}
components/Todo.js
import React, { Component, PropTypes } from 'react'
export default class Todo extends Component {
render() {
return (
<li>
{this.props.text}
</li>
)
}
}
58
ReactJS
components/TodoList.js
import React, { Component, PropTypes } from 'react'
import Todo from './Todo.jsx'
When we start the app, we will be able to add items to our list.
59
ReactJS
17. ReactJS ─ Animations
App.jsx
import React from 'react';
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
<h1>My Element...</h1>
</ReactCSSTransitionGroup>
</div>
60
ReactJS
);
}
}
export default App;
main.js
import React from 'react'
import ReactDOM from 'react-dom';
import App from './App.jsx';
css/style.css
.example-appear {
opacity: 0.01;
}
.example-appear.example-appear-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
61
ReactJS
App.jsx
import React from 'react';
var ReactCSSTransitionGroup = require('react-addons-css-transition-group');
handleAdd() {
var newItems = this.state.items.concat([prompt('Create New Item')]);
this.setState({items: newItems});
}
handleRemove(i) {
var newItems = this.state.items.slice();
newItems.splice(i, 1);
this.setState({items: newItems});
}
render() {
var items = this.state.items.map(function(item, i) {
return (
<div key = {item} onClick = {this.handleRemove.bind(this, i)}>
{item}
</div>
);
62
ReactJS
}.bind(this));
return (
<div>
<button onClick = {this.handleAdd}>Add Item</button>
main.js
import React from 'react'
import ReactDOM from 'react-dom';
import App from './App.jsx';
css/style.css
.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.example-leave {
opacity: 1;
63
ReactJS
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 500ms ease-in;
}
When we start the app and click the Add Item button, the prompt will appear.
Once we enter the name and press OK, the new element will fade in.
64
ReactJS
Now we can delete some of the items (Item 3...) by clicking it. This item will fade out
from the list.
65
18. ReactJS ─ Higher Order ComponentsReactJS
Higher order components are JavaScript functions used for adding additional functionalities
to the existing component. These functions are pure, which means they are receiving data
and returning values according to that data. If the data changes, higher order functions
are re-run with different data input. If we want to update our returning component, we
don't have to change the HOC. All we need to do is change the data that our function is
using.
Higher Order Component (HOC) is wrapping around "normal" component and provide
additional data input. It is actually a function that takes one component and returns
another component that wraps the original one.
Let us take a look at a simple example to easily understand how this concept works.
The MyHOC is a higher order function that is used only to pass data to MyComponent.
This function takes MyComponent, enhances it with newData and returns the enhanced
component that will be rendered on the screen.
var newData = {
data: 'Data from HOC...',
}
66
ReactJS
</div>
)
}
}
Note: Higher order components can be used for different functionalities. These pure
functions are the essence of functional programming. Once you are used to it, you will
notice how your app is becoming easier to maintain or to upgrade.
67
ReactJS
19. ReactJS ─ Best Practices
In this chapter, we will list React best practices, methods, and techniques that will help us
stay consistent during the app development.
PropTypes − The PropTypes should always be defined. This will help is track all
props in the app and it will also be useful for any developer working on the same
project.
Render − Most of the app's logic should be moved inside the render method. We
should try to minimize logic in component lifecycle methods and move that logic in
the render method. The less state and props we use, the cleaner the code will be.
We should always make the state as simple as possible. If we need to calculate
something from the state or props, we can do it inside the render method.
Higher Order Components (HOC) − Former React versions offered mixins for
handling reusable functionalities. Since mixins are now deprecated, one of the
solutions is to use HOC.
68