Connecting components to the store

A good design rule, separating concerns, says that you shouldn't directly connect a component to the store, but rather create a new component, a connected one, that will get whatever is needed from the store and pass it on to the original component. This rule will simplify, for example, all of our testing: our basic components will still receive everything via props, and we won't have to do any mocking of the store or anything like that in order to test them.

A good article on defining components, by Dan Abramov, is Presentational and Container Components, at https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0. More on this can be found in Container Components, at https://medium.com/@learnreact/container-components-c0e67432e005.

So, following that rule, for each component we want to connect, we'll add a new connected version. In our case, the connected version of the count will be the following, so the count prop of the component will receive the state.count value:

// Source file: src/counterApp/counter.connected.js

/* @flow */

import { connect } from "react-redux";

import { Counter } from "./counter.component";

const getProps = state => ({ count: state.count });

export const ConnectedCounter = connect(getProps)(Counter);

Similarly, the component to display the total number of clicks will be connected in a similar fashion:

// Source file: src/counterApp/clicksDisplay.connected.js

/* @flow */

import { connect } from "react-redux";

import { ClicksDisplay } from "./clicksDisplay.component";

const getProps = state => ({
clicks: state.clicks
});

export const ConnectedClicksDisplay = connect(getProps)(ClicksDisplay);

We will place those connected components in our main code, and they will get the values from the store, and pass them on to our original components, which will be totally unchanged.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset