Welcome Guest! (App Version 3.1)

websitnero logo name

React Redux Example

Using React in React

To use Redux in ReactJS we have to install a couple of libraries. So, first of all lets install both of these items.

To use redux enter the following commands:

> npm install redux

> npm install react-redux

Steps to implement redux:

Here we will see what all steps we need to take to implement our application with redux. Kindly, follow the steps below:

  1. Use the following structure of files and make separate folders for content and redux.

File Structure:

  1. In index.js import provider and store and use them.
  2. In app.js import HomeContainer.js and use it.
  3. Add home.js in components folder and use passed props (from container) to display values and call functions.
  4. In container file use mapStateToProps and mapDispatchToProps to send state and functions to the related component (here home.js). Use connect to bind both values and send to the component.
  5. In store folder, make a file named store.js and create a store into it with the help of RootReducer.
  6. Finally, in Reducer folder, make 3 files - index.js, reducer1.js and reducer2.js. Use CombineReducers to combine 2 or more reducers.

Full Redux Example

Go through the following files to understand how to make a simple react-redux example:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'; 
import store from './redux/store/store';

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>, 
    document.getElementById('root')
);

serviceWorker.unregister();

App.js

import React from 'react';
import './App.css';
import HomeContainer from './content/containers/home-container';

function App() {
  return (
    <div className="App">
      <HomeContainer></HomeContainer>
    </div>
  );
}

export default App;

home.js

import React, { Component } from 'react';

class Home extends Component {

  render(){
    return(
     <div>
        <ul>
          <li>Name is: {this.props.name}</li>
          <li>Age is: {this.props.age}</li>
          <li>Country is: {this.props.country}</li>
          <li>Total Books in Library: {this.props.noOfBooks}</li>
          <li>Library Head: {this.props.libraryHead}</li>
          <li>Library is in City: {this.props.libraryCity}</li>
        </ul>
        <p>
          <button onClick={this.props.increaseAge}>Increase Age</button>
          <button onClick={this.props.decreaseAge}>Decrease Age</button>
          <button onClick={this.props.increaseBooks}>Increase Books</button>
          <button onClick={this.props.decreaseBooks}>Decrease Books</button>
          <button onClick={this.props.changeCity}>Change City of Library</button>
        </p>
      </div>
    )
  }
}

export default Home;

home-container.js

import { connect } from 'react-redux';
import Home from '../components/home';

const mapStateToProps = (state, ownProps) => {
  return {
    name: state.reducer1.name,
    age: state.reducer1.age,
    country: state.reducer1.country,
    noOfBooks: state.reducer2.noOfBooks,
    libraryHead: state.reducer2.libraryHead,
    libraryCity: state.reducer2.libraryCity
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    increaseAge() {
      dispatch({type: "INCREASE_AGE"});
    },
    decreaseAge(){
      dispatch({type: "DECREASE_AGE"});
    },
    increaseBooks(){
      dispatch({type: "INCREASE_BOOKS"})
    },
    decreaseBooks(){
      dispatch({type: "DECREASE_BOOKS"})
    },
    changeCity(){
      dispatch({type: "CHANGE_CITY", payload: {city: "London"}})
    }
  }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Home);

store.js

import { createStore } from 'redux'; 
import RootReducer from '../reducers/index'; 

const store = createStore(RootReducer);

export default store;

reducers/index.js

import { combineReducers } from "redux";
import reducer1 from "./reducer1";
import reducer2 from "./reducer2";

export default combineReducers({ reducer1, reducer2 });

reducer1.js

const initialState = {
  name: "Peter Martin",
  age: 29,
  country: "USA"
};

export default function(state = initialState, action) {

  switch (action.type) {
    case "INCREASE_AGE": {
       return {
        ...state,
        age: state.age + 1
      };
    }
    case "DECREASE_AGE": {
       return {
        ...state,
        age: state.age - 1
      };
    }
    default:
      return state;
  }
}

reducer2.js

const initialState = {
  noOfBooks: 1000,
  libraryHead: "Lily Jane",
  libraryCity: "Chicago"
};

export default function(state = initialState, action) {

  switch (action.type) {
    case "INCREASE_BOOKS": {
       return {
        ...state,
        noOfBooks: state.noOfBooks + 1
      };
    }
    case "DECREASE_BOOKS": {
       return {
        ...state,
        noOfBooks: state.noOfBooks - 1
      };
    }
    case "CHANGE_CITY": {
      return{
        ...state,
        libraryCity: action.payload.city
        }
    }
    default:
      return state;
  }
}

Output

File Structure:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.