Skip to content

Instantly share code, notes, and snippets.

@swissmanu
Last active September 11, 2018 07:43
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 swissmanu/99dc6e424e3ac2446c2e7d6e49a882ba to your computer and use it in GitHub Desktop.
Save swissmanu/99dc6e424e3ac2446c2e7d6e49a882ba to your computer and use it in GitHub Desktop.
A wrapper component providing state to a stateless React component in TypeScript.
// setState signature borrowed from react 😇
interface WithStateProps<S> {
initialState: S;
children: (
state: S,
setState: <K extends keyof S>(
state: ((prevState: Readonly<S>, props: {}) => Pick<S, K> | S | null) | (Pick<S, K> | S | null),
callback?: () => void
) => void
) => React.ReactChild;
}
class WithState<S> extends React.PureComponent<WithStateProps<S>, S> {
constructor(props: WithStateProps<S>) {
super(props);
this.state = props.initialState;
}
render() {
return this.props.children(this.state, this.setState.bind(this));
}
}
// Example:
<WithState initialState={{ value: 100000 }}>
{({ value }, setState) => (
<NumberInput name="value" value={value} onChange={v => setState({ value: v })} />
)}
</WithState>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment