Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an autonomous React / Redux Component embeddable and distributable

I am building a React component that will be distributed via npm. The component uses Redux for its state and has the following use cases:

  1. Embedded as a standalone component on a regular webpage where the component itself is at the root of the React application.
  2. Embedded within a greater React app where a <Provider> and Redux store is already created by the consumer at the root of their application.

Since Redux requires that a <provider> and store be created at the root of the app, how can I distribute the component so that it can be used both ways?

like image 624
peterhry Avatar asked Jun 02 '26 04:06

peterhry


1 Answers

This is very interesting. But as an idea, why not give the consumer the ability to take your components reducer and put it in the store.. And when he wants to integrate your component, just give him the ability to provide the key where your component can get the props from.

For example the consumer creates his store reducers:

var rootReducer = combineReducers({
   someStuffReducer,
   externalComponent: yourComponentReducer
})

Then pass the key of the reducer to your component:

<YourComponent stateKey="externalComponent" />

In your Component you could take the ownProps and check if the stateKey is present:

// YourComponent mapStateToProps
function mapStateToProps(state, ownProps) {
  let stateKey = ownProps.stateKey || "yourDefaultKey" // or some logic.. you got the idea
  return {
    myComponentsState: state[stateKey]
  };
}

This will provide a simple way to make your component distributable, with a little config overhead for your consumers, but in fact if they are using Redux, it should be a piece of cake.

As Conclusion

Why do you need to provide a separate store? it will produce much more headache and programming overhead. You just need your reducer, to be included in the appStore of your consumer, thats it.

Notes

Your ACTION_TYPES would be global to the whole store, but if you give them a prefix for example and also write them into the README, then it is not that bad, because your consumers would be able to call them outside of your component, if needed.

like image 119
webdeb Avatar answered Jun 04 '26 13:06

webdeb