Last active
September 11, 2018 07:43
-
-
Save swissmanu/99dc6e424e3ac2446c2e7d6e49a882ba to your computer and use it in GitHub Desktop.
A wrapper component providing state to a stateless React component in TypeScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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