Last active
April 26, 2018 12:23
-
-
Save disintegrator/db23401c16d40e375171eaf31d371d9a to your computer and use it in GitHub Desktop.
Value component
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
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