Skip to content

Instantly share code, notes, and snippets.

@disintegrator
Last active April 26, 2018 12:23
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 disintegrator/db23401c16d40e375171eaf31d371d9a to your computer and use it in GitHub Desktop.
Save disintegrator/db23401c16d40e375171eaf31d371d9a to your computer and use it in GitHub Desktop.
Value component
import * as React from "react";
interface Props<T> {
initial?: T;
children: (r: { value?: T; onChange: (value: T) => void }) => React.ReactNode;
}
interface State<T> {
value?: T;
}
/**
* This component can be used to maintain some state and a change handler for
* it. It is especially useful when testing controlled components.
*/
export default class Value<T = any> extends React.Component<
Props<T>,
State<T>
> {
public state: Readonly<State<T>> = { value: this.props.initial };
public handleChange = (value: T) => {
this.setState({ value });
};
public render() {
const { value } = this.state;
return this.props.children({ value, onChange: this.handleChange });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment