Created
April 8, 2018 22:11
-
-
Save fusionstrings/da338677cebf283b70f72ae8410597da to your computer and use it in GitHub Desktop.
reusable redux connection using render prop
This file contains hidden or 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 from 'react'; | |
import { bindActionCreators } from 'redux'; | |
import { connect } from 'react-redux'; | |
import { | |
someAction, | |
anotherAction | |
} from './actions.js'; | |
class ReduxConnectionProvider extends React.Component { | |
componentDidMount() { | |
this.props.actions.someAction(); | |
} | |
render() { | |
const { component, render, children, actions, api } = this.props; | |
const props = { | |
anotherAction: actions.anotherAction, | |
api | |
}; | |
if (component) { | |
return React.createElement(component, props); | |
} | |
if (render) { | |
return render(props); | |
} | |
if (typeof children === 'function') { | |
return children(props); | |
} | |
if (children) { | |
return children; | |
} | |
return false; | |
} | |
} | |
const mapStateToProps = state => ({ | |
api: state.api | |
}); | |
const mapDispatchToProps = dispatch => ({ | |
actions: bindActionCreators( | |
{ | |
someAction, | |
anotherAction | |
}, | |
dispatch | |
) | |
}); | |
export default connect(mapStateToProps, mapDispatchToProps)( | |
ReduxConnectionProvider | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment