Introduction to Integrating React Component with Redux Store

Introduction

In the previous series, we learned about the basic concept of Redux and how it works as a standalone. Now in this article, we will be going to learn Redux with React. How we can setup Redux in a React project. 

Redux setup in React App

First, we will create a React application to get started with the React-Redux application by using the command:

npx create-react-app

So, after the execution of the command, the project is successfully executed,

Now after successful creation of the project, we will install 2 important packages

npm install redux react-redux

After successfully adding packages, it will be updated in package.json

Now in src folder create a new folder named components,

Now create UserContainer.js file,

Add code in UserContainer.js,

import React from 'react'  
  
function UserContainer() {  
    return (  
        <div>  
            <input type="text" placeholder="User Name"/>  
            <input type="text" placeholder="Password"/>  
            <button>Login</button>  
        </div>  
    )  
}  
  
export default UserContainer 

Add the UserContainer in App.js,

import React from 'react';  
import './App.css';  
import UserContainer from './components/UserContainer';  
  
function App() {  
  return (  
    <div className="App">  
     <UserContainer/>  
    </div>  
  );  
}  
  
export default App; 

And run the project, the output will be displayed as below,

Now for the next step, we will be creating a new folder named Redux,

Now following our folder structure, we will create folders feature-wise. Create a folder named login which will include all actions and constants related to login feature

Now let’s create an action named as loginActions.js,

const loginUser = () => {  
    return {  
        type: ‘LOGIN’,  
  
    }  
}  

After the action is successfully created, we will create type so instead of using a string in the single quote we can use it as constant, loginTypes.js

export const LOGIN = 'LOGIN'

After creating Type file, it will be imported in action to use constant directly,

import { LOGIN } from './loginTypes'  
export const loginUser = () => {  
    return {  
        type: LOGIN,  
        userName:'user',  
        password:'user'  
    }  
}   

Now we will create Reducer named loginReducer.js,

import { LOGIN } from './loginTypes'  
  
function callLoginApi(username, password) {  
    if (username === 'admin' && password === 'admin') {  
        return "Login Success";  
    } else {  
        return 'Invalid email and password';  
    }  
}  
  
const initialState = {  
    userName: 'test',  
    password: 'test',  
    loggedInStatus: ''  
}  
  
const loginReducer = (state = initialState, action) => {  
    switch (action.type) {  
        case LOGIN: return {  
            ...state,  
            userName: action.userName,  
            password: action.password,  
            loggedInStatus: callLoginApi(action.userName, action.password)  
        }  
        default: return state  
    }  
}  
  
export default loginReducer   

After creating reducer, we will create store.js file,

import {createStore} from 'redux'  
import loginReducer from './login/loginReducer'  
  
const store = createStore(loginReducer)  
  
export default store  

Now so far, we are done with Action, type, store, and Reducer. Now in the next step, we are using it in our container, 

First, we will create a constant named mapStateToProp which will map property in the container,

const mapStateToProp = state =>{  
    return{  
        userName:state.userName,  
        password:state.password  
    }  
} 

mapStateToProps – This function itself is suggested by its name. It acts as the connector between the Redux state to the react component. In this way, a connected React component will have access to the required store. 

Now we will connect our container with the action creator method. 

So, in a second step, we will create another function named mapDispatchToProps

const mapDispatchToProps = dispatch =>{  
    return{  
        login: ()=> dispatch(login())  
    }  
}  

mapDispatchToProps – This function is the same as mapStateToProps but that is for actions. mapDispatchToProps connects Redux action to the props of the React component. By doing this a connected React component will be able to send data to the store.

So now to connect action creator with props and state, I have created an index.js file in which exported action creator method,

export {loginUser} from './login/loginActions'   

Now updating UserContainer.js file,

import { connect } from 'react-redux'  
import { loginUser } from '../redux'  
export default connect(mapStateToProp, mapDispatchToProps)(UserContainer)  

Now the whole UserContainer.js code will be as below,

import React from 'react'  
import { connect } from 'react-redux'  
import { loginUser } from '../redux'  
  
function UserContainer(props) {  
    return (  
        <div>  
            <input type="text" placeholder="User Name" onChange={(e) => { userName = e.target.value }} />  
            <input type="text" placeholder="Password" onChange={(e) => { password = e.target.value }} />  
            <button onClick={props.loginUser}>Login</button>  
            <p>{props.loggedInStatus}</p>  
        </div>  
    )  
}  
  
const mapStateToProp = state => {  
    return {  
        userName: state.userName,  
        password: state.password,  
        loggedInStatus: state.loggedInStatus  
    }  
}  
  
const mapDispatchToProps = dispatch => {  
    return {  
        loginUser: () => dispatch(loginUser())  
    }  
}  
  
export default connect(mapStateToProp, mapDispatchToProps)(UserContainer)  

So, after connecting Redux to React components, we will wrap it in with provider in App.js

import React from 'react';  
import './App.css';  
import { Provider } from 'react-redux'  
import store from './redux/store'  
import UserContainer from './components/UserContainer';  
  
function App() {  
  return (  
    <Provider store={store}>  
      <div className="App">  
        <UserContainer />  
      </div>  
    </Provider>  
  );  
}  
  
export default App;  

The provider acts as a wrapper in React applications and ais ware of the entire Redux store. So in this way the whole Redux-React application works. 

The output will be as below,

Now update username and password property in loginActions.js

import { LOGIN } from './loginTypes'  
export const loginUser = () => {  
    return {  
        type: LOGIN,  
        userName:'admin',  
        password:'admin'  
    }  
}  

Now the output will be as below,

Summary

In this article, we have learned about connecting the Redux store to the React component.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s