Skip to content

Instantly share code, notes, and snippets.

@jakoblind
Last active March 28, 2017 09:23
Show Gist options
  • Save jakoblind/9f91daea0e72bb934e53e6405f34581d to your computer and use it in GitHub Desktop.
Save jakoblind/9f91daea0e72bb934e53e6405f34581d to your computer and use it in GitHub Desktop.
Demonstration of two ways to manage React state. With recompose and with ES6 classes
// First we have our component which takes data and callback functions as props
const ProductDetails = ({ selectedColor, selectedSize, setSelectedColor, setSelectedSize }) => {
return (
<div>
<p>Selected color is: {selectedColor}</p>
<p>Selected size is: {selectedSize}</p>
<button onClick={() => setSelectedSize(64)}> set selected size 64</button>
<button onClick={() => setSelectedColor("green")}> set selected color to green </button>
</div>
);
};
// Now I will demonstrate two options of where you can "put" that state
// 1. In a Es6 wrapper class
class ProductDetailsContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedSize: 32,
selectedColor: "blue"
};
this.setSelectedSize = this.setSelectedSize.bind(this);
this.setSelectedColor = this.setSelectedColor.bind(this);
}
setSelectedSize(selectedSize) {
this.setState({ selectedSize });
}
setSelectedColor(selectedColor) {
this.setState({ selectedColor });
}
render() {
return (<ProductDetails
selectedColor={this.state.selectedColor}
selectedSize={this.state.selectedSize}
setSelectedColor={this.setSelectedColor}
setSelectedSize={this.setSelectedSize} />);
}
}
//2. In recompose (https://github.com/acdlite/recompose)
const enhance = compose(
withState("selectedColor", "setSelectedColor", "blue"),
withState("selectedSize", "setSelectedSize", 32)
);
const ProductDetails = enhance(ProductDetails);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment