Last active
February 22, 2017 17:51
-
-
Save jonjaques/63c92bcf045e7a0e8d1d5adc4d192349 to your computer and use it in GitHub Desktop.
A declarative state connector for React-Redux
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 from 'react' | |
import * as someActionCreators from './actions-creators' | |
import StateConnector from './state-connector' | |
export default function Usage(props) { | |
return <StateConnector selector="some.state[0].slice" as="things" actions={someActionCreators}> | |
<PresentationComponent /> | |
</StateConnector> | |
} | |
function PresentationalComponent(props) { | |
const {addThings, things} = props | |
return <div> | |
How Many? {things} | |
<button onClick={e => addThings()}> | |
Add Things | |
</button> | |
</div> | |
} |
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, PropTypes} from 'react' | |
import {bindActionCreators} from 'redux' | |
import {connect} from 'react-redux' | |
import get from 'lodash/get' | |
import set from 'lodash/set' | |
class StateConnector extends Component { | |
static propTypes = { | |
selector: PropTypes.string.isRequired, | |
actions: PropTypes.object.isRequired | |
} | |
render() { | |
// This is kind of a naive way to do this, could avoid the wrapping div | |
return <div> | |
{React.Children.map(this.props.children, child => { | |
return React.cloneElement(child, this.props) | |
})} | |
</div> | |
} | |
} | |
export default connect(mapStateToProps, mapDispatchToProps)(StateConnector) | |
function mapStateToProps (state, ownProps) { | |
const stateSlice = get(state, ownProps.selector) | |
if (ownProps.as) { | |
return set({}, ownProps.as, stateSlice) | |
} | |
return stateSlice | |
} | |
function mapDispatchToProps(dispatch, ownProps) { | |
return bindActionCreators(ownProps.actions, dispatch) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment