Learn Redux in 5 mins:Part 2

Published May 12, 2018Last updated May 16, 2018
Learn Redux in 5 mins:Part 2

In the previous part, we saw how to create a redux store,how to create reducers and action creator.In this part, we are going to connect our react app to the store.

Connecting React to Redux

Typically,you connect your store to the entry point of your react app.Here is how you do it if you have react router as your entry point:
First install the following dependency like so:

npm install react-redux

You make the store available to your router like so:

import React from "react";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "react-redux"; //<--new
import Home from "./Home"; //this is your home component or any other component of your choice

const Root = ({ store }) => (
  <Provider store={store}> //<--new
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
      </Switch>
    </BrowserRouter>
  </Provider> //<--new
);

export default Root;

Then in your index.js,which is the entry point, you inject your store like so:

import React from "react";
import ReactDOM from "react-dom";
import "./styles/index.css";
import registerServiceWorker from "./registerServiceWorker";
import Root from "./routes/Root";//here we imported our router
import store from "./store/store";// here we import our store

ReactDOM.render(
<Root store={store} />, // here we inject our store to our router
document.getElementById("root"));
registerServiceWorker();

Dispatching actions

First create a file, name it helpers.js and do this

import store from "../store/store"; //here we import our store
import { identify_user } from "../store/actions/action";// here we import the action creator we created in the first part of this tutorial

export const login = (email,password) => store.dispatch(identify_user(email,password)); //here we created a function we can call from anywhere in our app to help us dispatch this action

Connecting a component to the store

connection to the store can be done like so:

import React, { Component } from "react";
import { connect } from "react-redux";//<--new
import { login } from "./helpers"//<--importing our function from helpers.js

class Profile extends Component {
  constructor(props) {
    super(props);
    console.log(props) //you should be able to access your store as props in your component 
    }
    
    componentDidMount(){
    	login("test@test.com","abcd")//here we dispatch an action by calling the function we created in our helpers.js file
    }
    render(){
    return(
    <div></div>
    )
    }
    }

const mapStateToProps = state => state;//<-- this is where you select the portion of the store you need

export default connect(mapStateToProps)(Home);//<--this is where you connect your component to the store

That's it.You now have a Reduxified React app. Thank you for reading.
giphy.gif

Discover and read more posts from John Anisere
get started