Last active
May 23, 2018 15:15
-
-
Save micha149/594b9c6df8ab432a2d77a468006767ae to your computer and use it in GitHub Desktop.
Just testing around with clean functional react components and the question how to get state in a stateless function. The answer is composition.
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 PropTypes from 'prop-types'; | |
const propTypes = { | |
count: PropTypes.number.isRequired, | |
onIncrement: PropTypes.func.isRequired, | |
onDecrement: PropTypes.func.isRequired, | |
}; | |
const Counter = ({ count, onIncrement, onDecrement }) => ( | |
<div> | |
<span>{count}</span> | |
<button onClick={onIncrement}>Increment</button> | |
<button onClick={onDecrement}>Decrement</button> | |
</div> | |
); | |
Counter.propTypes = propTypes; | |
export default Counter; |
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 PropTypes from 'prop-types'; | |
import { connect } from 'react-redux'; | |
import { selectCount } from './selectors'; | |
import { increment, decrement } from './actions'; | |
import Counter from './Counter'; | |
const mapStateToProps = state => ({ | |
count: selectCount(state), | |
}); | |
const mapDispatchToProps = dispatch => ({ | |
onIncrement: () => dispatch(incremet()), | |
onDecrement: () => dispatch(decremet()), | |
}); | |
export default connect( | |
mapStateToProps, | |
mapDispatchToProps, | |
)(Counter); |
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 PropTypes from 'prop-types'; | |
import { | |
compose, | |
onlyUpdateForPropTypes, | |
setPropTypes, | |
withHandlers, | |
withState, | |
} from 'recompose'; | |
import Counter from './Counter'; | |
const propTypes = { | |
startCount: PropTypes.number.isRequired, | |
}; | |
export default compose( | |
onlyUpdateForPropTypes, | |
setPropTypes(propTypes), | |
withState('count', 'updateCounter', ({ startCount = 0 }) => startCount), | |
withHandlers({ | |
onIncrement: props => () => props.updateCounter(props.count + 1), | |
onDecrement: props => () => props.updateCounter(props.count - 1), | |
}), | |
)(Counter); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment