Created
March 24, 2017 08:25
-
-
Save acanimal/4cb09bb4188bd536dff3f4c3e6c50342 to your computer and use it in GitHub Desktop.
High Order Component to wrap a component with redux Provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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