Skip to content

Instantly share code, notes, and snippets.

@jonjaques
Last active February 22, 2017 17:51
Show Gist options
  • Save jonjaques/63c92bcf045e7a0e8d1d5adc4d192349 to your computer and use it in GitHub Desktop.
Save jonjaques/63c92bcf045e7a0e8d1d5adc4d192349 to your computer and use it in GitHub Desktop.
A declarative state connector for React-Redux
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>
}
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