reactjs / reactjs/react.dev

Conditionally controlled component with `value` and `defaultValue` properties

Aberta
#3,407 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Linguagem predominante
JavaScript
Estrelas
11.8k
Forks
7.9k
Merge médio
1d 11h
PRs com merge (30d)
11

Descrição

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 key property

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:

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?

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece pela documentação “You Probably Don’t Need Derived State”, “Forms” e “Uncontrolled Components” vinculada na issue. Compare as orientações existentes com o controlled/uncontrolled component pattern descrito aqui e, em seguida, determine se uma alteração na documentação é justificável e onde ela deve ficar.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
javascript, react
Domínio
documentation
Tipo de issue
Documentação
Dificuldade
5/5
Tempo estimado
Mais de uma semana
Status de atividade
Estagnada
Clareza
Precisa de esclarecimento
Facilidade para iniciantes
25/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.