Image

The Beginner’s Guide to React Redux

Redux is an open-source JavaScript library for managing the state of a web application. It is essential to know the state of each component in modern applications as they consist of different UI components that interact with each other. It is typically done at the component level in a framework like React.

Redux enables you to manage the state of an entire application using a single immutable object. It allows users to easily manage the global state and access the state of any connected component. The best part is that Redux can be integrated into any application from applications running plain Javascript to ones using frameworks like React, Angular, and Vue. In this tutorial, we’ll be using React Redux — but there are very similar implementations for whatever type of application that you are creating.

Core Components of Redux

Redux introduces a couple of new components to an application to facilitate this state management.

  • ActionsActions are used to send data from the application to the Redux store. A typical action consists of the type property and an optional payload property.

  • ReducersThis is a function that accepts the current state and action as arguments and returns the updated state according to the action.

  • StoreThis is the heart of Redux where the state is stored. The state is kept in plain JavaScript objects and arrays.

Creating a Simple Redux Application

In this section, we’ll create a simple to-do application using React and Redux.

Step 1 — Create the sample React App

Install the create-react-app package, create an app named “redux-to-do” and install Redux.

npm install -g create-react-app

create-react-app redux-contact-app

npm install --save redux react-redux

Step 2 — Create the folders for Redux

Create the actions, reducers, and store folders in the src folder to facilitate Redux functions, and then fill them with the following javascript files:

Step 3 — Create the Actions

First, in our actionTypes.js. We’ll export the actionType for every action object we create:

export const CREATE_NEW_TODO = 'CREATE_NEW_TODO';

export const REMOVE_TODO = 'REMOVE_TODO';

Step 4 — Create a toDoActions.js file.

This will hold all the actions of the application, which in our case are the create and delete actions.

import * as actionTypes from './actionTypes';
 
export const createToDo = (todo) => {
    return {
      type: actionTypes.CREATE_NEW_TODO,
      todo: todo
    }
};

export const deleteToDo = (id) => {
    return {
        type: actionTypes.REMOVE_TODO,
        id: id
    }
};

Step 5 — Create the Reducers

Create the toDoReducer.js file to connect the actions with the state stored in the Redux store:

import * as actionTypes from '../actions/actionTypes';
 
export default (state = [], action) => {
    switch (action.type){
     
      case actionTypes.CREATE_NEW_TODO:
      return [
        ...state,
        Object.assign({}, action.todo)
      ];
      case actionTypes.REMOVE_TODO:
      return state.filter((data, i) => i !== action.id);
      default:
            return state;
    }
  };

Additionally, create an index.js file in the reducers folder to combine the reducers.

import { combineReducers } from 'redux';
import todo from './toDoReducer';
 
export default combineReducers({
    todo: todo
});

Step 6 — Create the Store

Create a file named configureStore.js to initialize the store and connect to the reducers.

import { createStore } from 'redux';
import rootReducer from '../reducers';
 
export default function configureStore(initialState) {
    return createStore(rootReducer, initialState);
}

Step 7 — Update the index.js file in the application root

We will import the react-reduce provider and store and wrap the component with the Redux store.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// Redux Import
import { Provider } from 'react-redux';
import reportWebVitals from './reportWebVitals';
 
// Store
import configureStore from './store/configureStore';
 
const store = configureStore();
 
ReactDOM.render(
  // Provider
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);
 
reportWebVitals();

Step 8 — Update the App.js File

In this step, we will render the application with the specified components and connect with Redux to obtain the state of each component.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as toDoAction from './actions/toDoAction';
 
class App extends Component {
 
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
      name: ''
    }
  }
 
  handleChange(e){
    this.setState({
      name: e.target.value
    })
  }
 
  handleSubmit(e){
    e.preventDefault();
    let todo = {
      name: this.state.name
    }
    this.setState({
      name: ''
    });
    this.props.createToDo(todo);
  }
 
  // View ToDo List
  listView(data, index){
    return (
      <div className="row">
        <div className="col-md-10">
          <li key={index} className="list-group-item clearfix">
            {data.name}
          </li>
        </div>
        <div className="col-md-2">
          <button onClick={(e) => this.deleteToDo(e, index)} className="btn btn-danger">
            Remove
          </button>
        </div>
    </div>
    )
  };
 
  deleteToDo(e, index){
    e.preventDefault();
    this.props.deleteToDo(index);
  }
 
  // Render the Form
  render() {
    let name;
    return(
      <div>
        <h1>Simple To-Do Application</h1>
        <hr />
        <div>
          <h3>Add Task </h3>
          <form onSubmit={this.handleSubmit}>
            <input type="text" onChange={this.handleChange} className="form-control" value={this.state.name}/><br />
            <input type="submit" className="btn btn-success" value="ADD"/>
          </form>
          <hr />
          { <ul className="list-group">
            {this.props.todo.map((todo, i) => this.listView(todo, i))}
          </ul> }
        </div>
      </div>
    )
  }
}
 
// Manage Props
const mapStateToProps = (state, ownProps) => {
  return {
    todo: state.todo
  }
};
 
const mapDispatchToProps = (dispatch) => {
  return {
    createToDo: todo => dispatch(toDoAction.createToDo(todo)),
    deleteToDo: index => dispatch(toDoAction.deleteToDo(index))
  }
};
 
export default connect(mapStateToProps, mapDispatchToProps)(App);

Note — The CSS classes are derived from the Bootstrap CSS framework. So you will have to link the Bootstrap stylesheet with the application. It can be done by adding the URL of the Bootstrap CSS file to the head section of the index.html file in your public folder.

Step 8 — Run the application

Use the npm run command to build and run the application. It will start the application on your default browser. Add some tasks and try it out.

That’s it and you have successfully created a to-do application that manages the state via Redux!

If your local machine is slowing your development down, try Codesphere. Codesphere is an intuitive web IDE and cloud provider that lets you code, debug, and deploy all with the power of the cloud!

Happy Coding!

Ref : The Beginner’s Guide to React Redux


aung thu oo

#HIRE ME

OPEN TO WORK

Ko Aung Thu Oo

Having over 15 years of working experience in Laravel, PHP, Flutter, Node.Js, Vue.JS, JAVA. Strong information technology professional with a degree i...

View detail