Skip to content

Instantly share code, notes, and snippets.

@fusionstrings
Created April 8, 2018 22:11
Show Gist options
  • Save fusionstrings/da338677cebf283b70f72ae8410597da to your computer and use it in GitHub Desktop.
Save fusionstrings/da338677cebf283b70f72ae8410597da to your computer and use it in GitHub Desktop.
reusable redux connection using render prop
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