Conditionally controlled component with `value` and `defaultValue` properties
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- JavaScript
- Estrellas
- 11.8k
- Forks
- 7.9k
- Merge medio
- 1 d 11 h
- PR fusionados (30 d)
- 11
Descripción
In our project codebase there is an uncontrolled component that allows you to specify an initial value with value property (code examples are simplified just to show an idea):
const CustomInput = ({ value = '', onChange }) => {
const [uncontrolledValue, setUncontrolledValue] = useState(value);
const handleChange = (e) => {
setUncontrolledValue(e.target.value);
if (onChange) {
onChange(e.target.value);
}
}
return <input value={uncontrolledValue} onChange={handleChange} />
}
This component is used inside the complex form (other input components in this form are controlled). Resetting the form causes problems with this particular component because it doesn't update the internal value on props change. There is the article that recommends 2 possible solutions:
- rewrite component to be controlled one
- trigger force rerender of the component using
keyproperty
IMO there is another option available - make component controlled/uncontrolled depending on existence value property:
const CustomInput = ({ value: controlledValue, defaultValue = '', onChange }) => {
const [uncontrolledValue, setUncontrolledValue] = useState(defaultValue);
const isControlled = value !== undefined;
const value = isControlled ? controlledValue : uncontrolledValue;
const handleChange = (e) => {
if (!isControlled) {
setUncontrolledValue(e.target.value);
}
if (onChange) {
onChange(e.target.value);
}
}
return <input value={value} onChange={handleChange} />
}
This approach allows custom components to act as a standard <input /> element. I saw it in @kentcdodds video lesson and also in some popular libraries sources. But I can't find anything about such an approach in official react documentation. defaultValue is mentioned only here:
- https://reactjs.org/docs/dom-elements.html#value
- https://reactjs.org/docs/uncontrolled-components.html#default-values
Should this approach be added as a recommendation in You Probably Don't Need Derived State or Forms article? If not are there any pitfalls to consider it as bad practice / anti-pattern?
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con la documentación «You Probably Don’t Need Derived State», «Forms» y «Uncontrolled Components» enlazada en el issue. Compara sus indicaciones actuales con el controlled/uncontrolled component pattern descrito aquí y determina después si está justificado cambiar la documentación y dónde debería ubicarse.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- javascript, react
- Área
- documentation
- Tipo de issue
- Documentación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100