Skip to content

Instantly share code, notes, and snippets.

@acanimal
Created March 24, 2017 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acanimal/4cb09bb4188bd536dff3f4c3e6c50342 to your computer and use it in GitHub Desktop.
Save acanimal/4cb09bb4188bd536dff3f4c3e6c50342 to your computer and use it in GitHub Desktop.
High Order Component to wrap a component with redux Provider
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import initialState from './store/initialState';
import createStore from './store/createStore';
const store = createStore(initialState);
const getDisplayName = WrappedComponent => WrappedComponent.displayName || WrappedComponent.name || 'WrappedComponent';
/**
* HOC to wrap a component within redux provider to allow access the store.
*/
export default (WrappedComponent) => {
class WrappedComponentWithRedux extends Component {
static displayName = `WrappedComponentWithRedux(${getDisplayName(WrappedComponent)})`;
/**
* Wrapper function to call getInitialProps of the wrapped component.
*/
static getInitialProps(context) {
if (typeof WrappedComponent.getInitialProps === 'function') {
return WrappedComponent.getInitialProps(context);
}
return null;
}
render() {
return (
<Provider store={store}>
<WrappedComponent {...this.props} />
</Provider>
);
}
}
return WrappedComponentWithRedux;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment