Skip to content

Instantly share code, notes, and snippets.

@reciosonny
Last active December 25, 2018 07:00
Show Gist options
  • Select an option

  • Save reciosonny/caa63b2d69de3a28a6188fea9a654afd to your computer and use it in GitHub Desktop.

Select an option

Save reciosonny/caa63b2d69de3a28a6188fea9a654afd to your computer and use it in GitHub Desktop.
const initialState = {
numberOfPeople: 10,
slicesPerPerson: 2,
};
//We then use this HOC like so: WithCalculator(**component goes here**)
//This makes use of arrow functions(=>) and anonymous class construction(returns `class`)
const WithCalculator = WrappedComponent => {
return class extends Component {
static displayName = `WithCalculator(${WrappedComponent.displayName ||
WrappedComponent.name})`;
state = { ...initialState };
updateNumberOfPeople = event => {
const numberOfPeople = parseInt(event.target.value, 10);
this.setState({ numberOfPeople });
};
updateSlicesPerPerson = event => {
const slicesPerPerson = parseInt(event.target.value, 10);
this.setState({ slicesPerPerson });
};
reset = event => {
this.setState({ ...initialState });
};
render() {
const { numberOfPeople, slicesPerPerson } = this.state;
const numberOfPizzas = calculatePizzasNeeded(
numberOfPeople,
slicesPerPerson,
);
return (
<WrappedComponent
numberOfPeople={numberOfPeople}
slicesPerPerson={slicesPerPerson}
numberOfPizzas={numberOfPizzas}
updateNumberOfPeople={this.updateNumberOfPeople}
updateSlicesPerPerson={this.updateSlicesPerPerson}
/>
);
}
};
};
const WithCalculator = WrappedComponent => {
return class extends Component {
static displayName = `WithCalculator(${WrappedComponent.displayName ||
WrappedComponent.name})`;
state = { ...initialState };
updateNumberOfPeople = event => {
const numberOfPeople = parseInt(event.target.value, 10);
this.setState({ numberOfPeople });
};
updateSlicesPerPerson = event => {
const slicesPerPerson = parseInt(event.target.value, 10);
this.setState({ slicesPerPerson });
};
reset = event => {
this.setState({ ...initialState });
};
render() {
const { numberOfPeople, slicesPerPerson } = this.state;
const numberOfPizzas = calculatePizzasNeeded(
numberOfPeople,
slicesPerPerson,
);
return (
<WrappedComponent
numberOfPeople={numberOfPeople}
slicesPerPerson={slicesPerPerson}
numberOfPizzas={numberOfPizzas}
updateNumberOfPeople={this.updateNumberOfPeople}
updateSlicesPerPerson={this.updateSlicesPerPerson}
/>
);
}
};
};
//normal cons
function test (){
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment