Add connect and mapStateToProps functionality to the library

Aashish Karki
Sep 5, 2018 · 5 min read

So we have covered making a simple library and then adding a combineReducer functionality to it. Now we step up and make this library usable in a react app. But be sure you have gone through blogs before this as basic things are covered there.

We are going to manipulate the react components for this we need to add react to our own library , by using the command yarn add react. But the things is this won’t be enough now we need to transpile our es6 to es5 and then use that contents in our react app. So to do that we need to add babel transpiler for class properties and object spread so our package.json will look something like this :

{“name”: “redux-clone”,“version”: “0.1.0”,“description”: “a clone library similar to redux library”,“main”: “dist/index.js”,“files”: [“dist”],“author”: “Aashish Karki <aashish.y2z@gmail.com>”,“license”: “UNLICENSED”,“url”: “git@github.com:karkipy/redux-clone.git”,“private”: true,“peerDependencies”: { “react”: “>=16.3.0”},“devDependencies”: { “@babel/cli”: “⁷.0.0”, “@babel/core”: “⁷.0.0”, “@babel/plugin-proposal-object-rest-spread”: “⁷.0.0”, “@babel/preset-env”: “⁷.0.0”, “@babel/preset-flow”: “⁷.0.0”, “@babel/preset-react”: “⁷.0.0”, “react”: “>=16.3.0” “react-scripts”: “¹.1.5”},“scripts”: { “build”: “babel src — out-dir dist”, “test”: “echo \”Error: no test specified\” && exit 1"}}

notice that we use build to transpile our code and then in main you can see the entry point being dist/index.js after build command the whole source code will be transpiled into a dist folder. Now Moving forward with our application. We add a connect file : which contains the connect function of redux- react , a Container file which will be used a Provider and then Content file which has Provider and Consumer. So the files will be

PhaseThree folder Structure.

Jumping to the easiest, Content.js will have

import React from ‘react’;export const { Provider, Consumer } = React.createContext();

While using react-redux, we have the code such as

<Provider store={store}>
<App />
</Provider>

So to do that we will be using Container file which will read the props passed to it and then return the child as it is, So the file will be

import React, { Component } from ‘react’;
import { Provider } from ‘./Content’;
export default class Container extends Component {

constructor() {
super();
this.state = {};
}
render() { const { store } = this.props;

return (
<Provider value={{ store: store.getState() }}>
{this.props.children}
</Provider>
);
}
}

Now we will have only one instance of provider being used in the whole application so when calling the Consumer of the said Provider it will only respond to one value of that state which is what we wanted. Now we move forward to connect functionality. The structure for connect is something like this connect(mapStateToProps, mapDispatchToProps)(App). Lets simplify this type of structure first. For this take see this example,

const connect = (first, third = null) => (second) => {console.log(first,third, second);};connect(1)(2);

The output will be :

1, null , 2

see the second params is again a function call so we need to call it again. Now we add the said connect function. Which will be as :

import React from ‘react’;const { Consumer } = require(‘./Content’);export const connect = (stateToProps, stateToDispatch = null) => (AppComponent) => {  return class extends React.Component {     render() {      return (       <Consumer>
{value => {
const store = value.store;
// getting the value from the provider
const propsToReturn = stateToProps(store);
// call back to the props function to get the said props as // for mentioned
return (<AppComponent {…this.props} {…propsToReturn} />);
// return the unmutated component with new props
}} </Consumer> ) } }}

For now I will only deal with stateToProps , and plus stateToDispatch is optional in react-redux as well. Now we expose these functions into out index.js.

const createStore = require(‘./createStore’);const combineReducer = require(‘./combineReducer’);const Provider = require(‘./Container’).default;
// We can name it anything as it is being called in default
const { connect } = require(‘./connect’);module.exports = {
connect,
Provider,
createStore,
combineReducer,
};

So That’s it for our library , now on to testing as i have mentioned before our library and the test app lies on the same package making it interdependable so for this we will create a react app inside the package as :

Phase Three Test

Tip : you cannot create react app inside this package so create it outside and move it in the packages

Now in test-react-redux , in package mention our library name along with the version of it. Such as :

package.json of test-react app

we added redux-clone in our dependencies. Now simple as that we make a store with its reducer as (I am a bit lazy so added a screen shot but u can see that we have only one value i.e increment ):

store for our app

In App.js file of app we now call our said library as :

import React, { Component } from ‘react’;import { Provider, createStore } from ‘redux-clone’;import reducer from ‘./store/reducer’;import TestScreen from ‘./components/TestScreen’;const store = createStore(reducer);
class App extends Component {
render() { return ( <Provider store={store}> Let’s Test it Here <TestScreen /> </Provider> ); }}export default App;

Now Create a TestScreen as mentioned there and we will see if our connect function works. The TestScreen will be as

import React from ‘react’;import { connect } from ‘redux-clone’;const TestScreen = ({ increment }) => <div> Increment Value :{increment} </div>;const mapStateToProps = ({ increment }) => ({increment});export default connect(mapStateToProps)(TestScreen);

And The final output for this is

Final Output

Clap Clap !!! It has been finished

library code : https://github.com/karkipy/redux-clone/tree/phaseThree

To test this library

test code: https://github.com/karkipy/redux-clone/tree/phaseThree-Test

Aashish Karki

Written by

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade