Reusing Redux Containers with multiple Components in React.

Timi Ajiboye
chunks of code*
Published in
1 min readApr 26, 2018

If you’re using react-redux then you should be familiar with the code below.

// SomeContainer.jsxconst mapDispatchToProps = (dispatch) => ({
...
});
const mapStateToProps = (state) => ({
...
});
export default connect(matchStateToProps, matchDispatchToProps)(SomeComponent);

And then in your file that handles routing (or wherever). You’d have something like this.

<Route exact path="/some/path" component={ SomeContainer } />

This pattern is useful in separating data retrieval from it’s presentation but it can result in having way too many containers. Often enough you’ll find that containers aren’t that different from each other and that it makes sense to be able to reuse them.

Well, this code below will show how to do just that. Inspired by this stackoverflow answer.

let Components = {
'Component1': require('../path1.jsx').default,
'Component2': require('../path2.jsx').default
};
const mapDispatchToProps = (dispatch) => ({
...
});
const mapStateToProps = (state) => ({
...
});
export default = (componentName) => {
return connect(
matchStateToProps,
mapDispatchToProps
)(Components[componentName]);
}

And then in your file that handles routing (or wherever). You’d have something like this.

<Route exact pa... component={ SomeContainer('Component1') } />

And it can be used for Component2 as such:

<Route exact pa... component={ SomeContainer('Component2') } />

Needless to say, you can even conditionally match state/dispatch to props depending on the component that is to be rendered.

--

--

Timi Ajiboye
chunks of code*

I make stuff, mostly things that work on computers. Building Gandalf.