Primary Project for buinding the app with react and redux using “create-react-app” , which will helps you to understand how redux works with react js.
We need Node js V1.8.10 stable, “create-react-app” for develop the simple project with react and redux. Need some plugins related to “react js” named.
- React Router Dom
- Redux Thunk
- React Router Redux
- Redux Promise
- Axios
React Router is the standard routing library for React. It keeps your UI sync with the URL. it has a simple API with powerful features like Lazy code Loading, dynamic route matching and Location transition handling build right in. To know about react router you can go to this link “react-router”
Redux Thunk is middleware, which allows you to write action creators that return a function instead of a action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. To know redux thunk more about, you can go to this link “redux-thunk”.
React Router includes three main packages:
- react-router. This is the core package for the router.
- react-router-dom. It contains the DOM bindings for React Router. In other words, the router components for websites.
- react-router-native. It contains the React Native bindings for React Router. In other words, the router components for an app development environment using React Native.
The middleware returns a promise to the caller so that it can wait for the operation to finish before continuing. So Developer can add the .then
and .catch
after dispatch
any action at redux
.
You use Redux to manage your application state. You use React Router to do routing. All is good.But the two libraries don't coordinate. You want to do time travel with your application state, but React Router doesn't navigate between pages when you replay actions. It controls an important part of application state: the URL. This library helps you keep that bit of state in sync with your Redux store. We keep a copy of the current location hidden in state. When you rewind your application state with a tool like Redux DevTools, that state change is propagated to React Router so it can adjust the component tree accordingly. You can jump around in state, rewinding, replaying, and resetting as much as you'd like, and this library will ensure the two stay in sync at all times.
- Download git Repository
git clone https://github.com/tariqulislam/react-redux-sample/
- then Run Command for
npm install
- After that run command
npm start
oryarn start
Then I have create file named home.reducer.js
file at src/reducers
directory at project which will contains action constraint
, actions
, reducer
for Home Component
, state
for
- Add the
action constraint
tohome.reducer.js
which will show and hide the paragraph of home page
export const HIDE_HOME_INFO = 'HIDE_HOME_INFO'
export const SHOW_HOME_INFO = 'SHOW_HOME_INFO'
- Initialize the
state
of thereducer
by:
const initialState = {
showInfo: false
}
- Then add the action those action constraint.
export const showParagraphInfo = () => {
return dispatch => { dispatch({ type: SHOW_HOME_INFO })}
}
export const hideParagraphInfo = () => {
return dispatch => { dispatch({ type: HIDE_HOME_INFO })}
}
- Create the Reducer for
Home Component
athome.reducer.js
file
export default (state= initialState, action) => {
switch (action.type) {
case SHOW_HOME_INFO:
return {
...state,
showInfo: true
}
case HIDE_HOME_INFO:
return {
...state,
showInfo: false
}
default:
return state
}
}
- Then change the code at
src/core/rootReducer.js
file and addhome.reducer
for combine and resolve thehome module reducer
toredux store
import { combineReducers } from 'redux'
import home from '../reducers/Home/home.reducer'
const rootReducer = combineReducers({ home})
export default rootReducer
- Create
Home
component atsrc/components/Home.js
file at project - Import all dependency and reducer to connect with
redux
withHome
react component
import React, {Component} from 'react'
import { push } from 'react-router-redux'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
-
{Component}
andReact
ofreact
package help us to build theReact Component
. -
{ push }
ofreact-router-redux
package help toroute
from one component to another component -
{ bindActionCreators }
ofredux
package provide the feature to mapping action with any UIevent
and also tigger theredux
action which aredeclare
atredux action
-
{ connect}
is curry function ofreact-redux
package, which will make connect withreducer
of this componentconnect(mapStateToProps, mapDispatchToProps)(<Component name>)
-
mapStateToProps
: which will map all the state betweenredux reducer
andcomponent
-
mapDispatchToProps
: which will map all thedispatch
action withcomponent
UI’sevent
will take component name such asHome
class Home extends Component {
componentWillMount () {
this.props.hideParagraphInfo()
}
render () {
return (
<div>
Home Page
</div>
)
}
}
- I have extends the
React
Component
Class to createHome
Component React Component
, we needconstructor
,componentWillMount
,componentDidMount
andrender
functionconstructor
: constructor() If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for aReact component is called before it is mountedcomponentWillMount
: when the props and state are set, we finally enter the realm of Life Cycle methods. The first true life cycle method called is componentWillMount(). This method is only called one time, which is before the initial render. Since this method is called before render() function., we can declare anyredux
action
when component is loading.componentDidMount
: componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.- To Render element using
render()
function. The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.
const mapStateToProps = (state) => ({
showInfo: state.home.showInfo
})
const mapDispatchToProps = dispatch => bindActionCreators({
showParagraphInfo,
hideParagraphInfo,
goToAboutPage: () => push('/about-us')
}, dispatch)
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home)
mapStateToPorps
: containsshowInfo
reduxstate
which create themapping
through React Component to Redux StoremapStateToProps
: which will containsshowParagraphInfo
,hideParagraphInfo
andgoToAboutPage
redux function, which create mapping betweenhome.reducer
withHome
component- Then
connect
function connectHome
component with Redux Store. goToAboutPage1: () => push(‘/about-us’)
function change the route of thecomponent
and it will effect theredux store
of thehome
component andabout
component also.
componentWillMount () {
this.props.hideParagraphInfo()
}
this.props.hideParagraphInfo()
redux action
call in componentWilMount
to hide the paragraph of Home Page.
render () {
return ( <div>
<h1> Home Page</h1>
{!this.props.showInfo && <button onClick={() => this.props.showParagraphInfo()}> Show Paragraph </button>}
{this.props.showInfo && <button onClick={() => this.props.hideParagraphInfo()}>Hide Paragraph</button>}
{ this.props.showInfo && <p> this is paragraph</p>}
<button onClick={() => this.props.goToAboutPage()}> Go To About Page</button>
</div>
)
}
this.props.showParagraphInfo()
reduxaction
added inonClick
event to show the paragraph!this.props.showInfo
will check theredux store
provide theshowInfo
false, it will hideShow Paragraph
button andthis.props.showInfo
isredux store state
which helps react component to shows the paragraph atHome component
- For ajax request handling, we have to create
home.async.js
file atsrc/components/Home
directory - For learning purpose, we have to create function named
getAllPosts
which is async function to get all post from sample json web api site namedhttps://jsonplaceholder.typicode.com
- We are using
axios
package to get the data from json api.
import axios from 'axios'
export const getAllPosts = async () => {
const getAllPosts = await axios.get(
"https://jsonplaceholder.typicode.com/posts",
{
headers: {'Content-Type': 'application/json'}
}
)
return getAllPosts;
}
- Home Page initial load without paragraph