Skip to content

Instantly share code, notes, and snippets.

@micha149
Last active May 23, 2018 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micha149/594b9c6df8ab432a2d77a468006767ae to your computer and use it in GitHub Desktop.
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.
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;
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);
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