peterhry
peterhry

Reputation: 1130

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?

Upvotes: 3

Views: 622

Answers (2)

webdeb
webdeb

Reputation: 13211

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.

Upvotes: 4

AlexandruB
AlexandruB

Reputation: 688

Make your component check if context contains the store passed on by Provider.

  • If it's the case then apply your Redux specific logic.
  • If it's not the case manage your own local state but do offer the possibility for the parent to pass in the props object handlers so that parents are notified if data needs to be exchanged.

Upvotes: 2

Related Questions