This repository was archived by the owner on Mar 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
This repository was archived by the owner on Mar 4, 2020. It is now read-only.
AutoControlledComponent docs #1571
Copy link
Copy link
Closed
Labels
Description
AutoControlledComponent docs
Problem description
It is difficult for a user to understand how to use AutoControlledComponent.
For this scenario, let's assume we want to create an auto controlled component (MyAutoControlledComponent) for the value prop and pass it to an input.
Proposed solution - add documentation for AutoControlledComponent
Here is a list of steps and issues that should be documented:
type MyProps = { ... }
type MyState = { value: VALUE_TYPE, ... }
// #1
class MyAutoControlledComponent extends
AutoControlledComponent<MyProps, MyState> {
// #2
static autoControlledProps = ['value']
// #3
static propTypes = {
defaultValue: PROP_TYPE, // import * as PropTypes from 'prop-types'
value: PROP_TYPE,
}
// #4
static getAutoControlledStateFromProps(
props: MyProps,
state: MyState,
): Partial<MyState> {
return { ... }
}
// #5
getInitialAutoControlledState(props: MyProps): Partial<MyState> {
return { value: MY_DEFAULT_VALUE }
}
renderComponent({ ElementType }) {
// #6
const { value = '' } = this.state
return <ElementType {...}><input value={value} {...} /></ElementType>
}
}-
a template for how to extend
AutoControlledComponentclass -
the fact that we need to define a static array on the component class:
static autoControlledProps = ['value'] -
the fact that we need to define static
propTypesobject withvalueanddefaultValuekeys -
how to derive state from props:
usegetAutoControlledStateFromPropsinstead ofgetDerivedStateFromProps -
how to set default value for
value(when the user does not setvalueordefaultValue):
- use
getInitialAutoControlledStateclass method - note that
getInitialAutoControlledStatecannot be an arrow function:
class MyAutoControlledComponent extends AutoControlledComponent {
getInitialAutoControlledState = () => { // WON'T WORK!!!
return { value: MY_DEFAULT_VALUE }
}
// ...
}- (ONLY FOR INPUTS? WHY?) the fact that we need to use
''(empty string) as default value forthis.state.valuebefore passing it to an input, otherwise we get this React error:
Warning: A component is changing a controlled input of type range to be
uncontrolled. Input elements should not switch from controlled to uncontrolled
(or vice versa). Decide between using a controlled or uncontrolled input element
for the lifetime of the component.
More info: https://fb.me/react-controlled-components
Reactions are currently unavailable