Skip to content

Instantly share code, notes, and snippets.

@jrwebdev
Last active January 31, 2021 15:04
Show Gist options
  • Select an option

  • Save jrwebdev/3235dba972983859ed779c746393766d to your computer and use it in GitHub Desktop.

Select an option

Save jrwebdev/3235dba972983859ed779c746393766d to your computer and use it in GitHub Desktop.
export interface InjectedCounterProps {
value: number;
onIncrement(): void;
onDecrement(): void;
}
interface MakeCounterProps {
minValue?: number;
maxValue?: number;
}
interface MakeCounterState {
value: number;
}
const makeCounter = <P extends InjectedCounterProps>(
Component: React.ComponentType<P>
) =>
class MakeCounter extends React.Component<
Subtract<P, InjectedCounterProps> & MakeCounterProps,
MakeCounterState
> {
state: MakeCounterState = {
value: 0,
};
increment = () => {
this.setState(prevState => ({
value:
prevState.value === this.props.maxValue
? prevState.value
: prevState.value + 1,
}));
};
decrement = () => {
this.setState(prevState => ({
value:
prevState.value === this.props.minValue
? prevState.value
: prevState.value - 1,
}));
};
render() {
const { minValue, maxValue, ...props } = this.props;
return (
<Component
{...props as P}
value={this.state.value}
onIncrement={this.increment}
onDecrement={this.decrement}
/>
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment