We are creating a large front-end application.
We are using React-Redux for it
We are creating some reusable components.
**This question is regarding having multiple instance of same reusable redux react components on the same page/route **
Problem details:
We have a Sectionheader component.Which is bound to redux state.
It listens to the header property reducer SectionheaderReducer.
As we have 2 instances of this Sectionheader on the page both tend to show same values as they are bound to the same store state-property.
How to make the redux based reusable react component configurable.So that each instance can have different value of header property for reducer SectionheaderReducer
I've implemented it in a different way, without actually changing the action name with a namespace.
Rather, I added infra functions which will intercept the action creators and add
meta-data
to each action. (followingFSA
) That way you don't need to change your reducer or themapStateToProps
function.Also it is compatible with
redux-thunk
.Should be easy to use... reducer-action-interceptor
I interpreted the question to mean:
<SectionHeader />
)One possible solution would have you add the idea of "sections" to your store. You'd create reducers that manage the content structure of the data. E.G. the store state, at one time, may look like this:
```
You would then have a "container component" or "layout component" or "smart component" (they have many names), that "knows" that you want to use section 2 and section 4 on a particular page. How it knows this, is up to you. Perhaps you hard-code the indices (because it will always be the same), perhaps you have a filtering rule, perhaps you have another field in the store which defines the choices... etc.
The container component would then pass the chosen heading into the "dumb" , perhaps like this:
or
You need to implement some way of namespacing the instances. This can be as basic as passing in a key to differentiate the components and reducers.
You can use the
ownProps
in yourmapStateToProps
function to guide the mapping to a namespaceThe same method can be used to pass on a namespace to the
mapDispatchToProps
Just remember to use the namespace in the action type so the reducers don't tread on toes
And make sure the reducer is namespaced too
Now add the 2 namespaced reducers when combining reducers
Finally pass the namespace to each instance
Disclaimer: I am the main contributor on the following library.
redux-subspace can provide a more advanced namespacing implementation without you having to reimplement this pattern for every component you want to have multiple instances for.
Creating the reducers is similar to above
Then
SubspaceProvider
can be used to switch out the state for each componentJust ensure you also change your
mapStateToProps
function to so start traversing from the subtree mapped in the providerThere is also a Higher-Order Component if you prefer to reduce nesting.