Friday, August 14, 2020

Adding Redux to a React App

In the previous few posts we saw about Action, Reducer and Store concepts about Redux. In this post we shall see on how to put all of these together to add a Redux store to a React application.

In this sample we will create a simple React application, with a textbox where the user can type his name and a button on click of which a Welcome message is displayed with the name. The onChange event of the textbox and the onClick event of the button will dispatch actions to update the corresponding property in redux store.
1. First we need to install the redux npm package, and since we are going to use redux store in a react application we need to install the react-redux package.

npm install redux --save
npm install react-redux –save

2. Next we create a Reducer, in the below sample we will create a homeReducer which will handle 2 actions.

const initialState = {
    name: '',
    greeting: ''
  };

export const homeReducer = function (state = initialState, action) {
    switch (action.type) {
      case "SET_NAME":
        return {
            ...state,
            name: action.payload.value
          };
      case "SET_GREETING":
        return {
            ...state,
            greeting: `Welcome ${action.payload.name} !!!`
          };
      default:
        return state;
    }
  };

3. Next we need to create the store using the reducer as follows.

import { combineReducers, createStore } from 'redux';
import { homeReducer } from './homeReducer';

export const store = createStore(homeReducer);

4. Next we need to warp our root Component inside a Provider and pass the redux store to Provider

mport React, { Component } from 'react';
import HomeReduxContainer from './Components/HomeReduxContainer';
import { Provider } from 'react-redux';
import { store } from './Redux/store';

class App extends Component {
  constructor() {
    super();
  }

   render() {
     return (
      <div className="container">
        <div className="row">
          <div className="col-md-12">
            <Provider store={store}>
                <HomeReduxContainer />
            </Provider>
          </div>
        </div>
      </div>
     );
   }
}

5. Next we will create a container component which will host the actual UI component. The container component will interact with the Redux store and pass the state properties as props to the UI component.

mapStateToProps will map 2 state properties name & greeting to local props, which will be passed to the UI component.

mapDispatchToProps will map 2 functions which will dispatch actions to set name and greetings in the redux store

We will pass all the state props to the UI component by passing {...this.props}

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { SetName, SetGreeting } from '../Redux/actions';
import HomeRedux from './HomeRedux';

class HomeReduxContainer extends Component {
   constructor() {
     super();
   }

   render() {
     return (
      <div>
        <HomeRedux {...this.props} />
      </div>
     );
   }
 }

function mapStateToProps(state) {
  return {
    name: state.name,
    greeting: state.greeting
  };
}
const mapDispatchToProps = dispatch => {
  return {
    setName: (value) => { dispatch(SetName(value)) },
    setGreeting: (name) => { dispatch(SetGreeting(name)) }
  }
};

export default HomeReduxContainer = connect(mapStateToProps, mapDispatchToProps)(HomeRedux);

6. Finally we will create the React component which will handle user inputs and display the greetings to the user. This components receives the state values as props from the container component, and call methods of the Container component to dispatch actions to redux.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { SetName, SetGreeting } from '../Redux/actions';

class HomeRedux extends Component {
   constructor(props) {
     super(props);
     this.handleChange = this.handleChange.bind(this);
     this.handleClick = this.handleClick.bind(this);
   }

   handleChange(event) {
    const { value } = event.target;
    this.props.setName(value);
   }

   handleClick(event) {
    this.props.setGreeting(this.props.name);
   }
    render() {
     return (
      <div>
         <form>
            <div className="form-group row">
              <label htmlFor="Name" className="col-md-2 col-form-label">Enter Name</label>
              <div className="col-md-4">
                <input type="text"
                  className="form-control"
                  value={this.props.name}
                  onChange={this.handleChange} />           
              </div> 
              <input type="button"
                className="btn btn-primary col-md-1"
                value="Click"
                onClick={this.handleClick} />           
            </div>
         </form>
         <br/>
        <span>{this.props.greeting}</span>
      </div>
     );
   }
 }

export default HomeRedux;

The output of the Application will be as follows.
When the user types in the textbox, the onChange event will call the setName function in the parent component which in turn will dispatch the SET_NAME action to the store to save the types name to the redux store.

When the user clicks on the button, the onClick event will call the setGreeting function in the parent component which in turn will dispatch the SET_GREETING action to the store to set the greeting to the redux store.




Search Flipkart Products:
Flipkart.com

No comments: