1

Im doing a Edit in React, when i click the button i get the name on the input but im getting this error:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Function:

editAluno(aluno) {
    this.aluno = aluno.nome
    this.setState({ aluno: aluno.nome })
}

HTML:

                    <button type="button" onClick={() => this.editAluno(aluno)}>[EDIT]</button>
  • 1
    Does this answer your question? [A component is changing an uncontrolled input of type text to be controlled error in ReactJS](https://stackoverflow.com/questions/47012169/a-component-is-changing-an-uncontrolled-input-of-type-text-to-be-controlled-erro) – SuperStormer Mar 24 '21 at 02:11
  • I tried but I still couldn't :/ – GuilhermeSO Mar 24 '21 at 02:55
  • Please try to include a [Minimal, Complete, and Reproducible Code Example](https://stackoverflow.com/help/minimal-reproducible-example) in your question. This example should probably include an input element that is (or isn't) being controlled. – Drew Reese Mar 24 '21 at 04:44

1 Answers1

0

That happens if aluno.nome is undefined or null,:

<input value={this.state.aluno.nome} ... />
// ☝️ <input value={undefined} will show that warning in this case

Try:

<input value={this.state.aluno.nome || ''} ... />
                                    ^^^^^^

Or, alternatively, do it in the setState call:

editAluno(aluno) {
  this.aluno = aluno.nome;
  this.setState({ aluno: aluno.nome || '' });
}
Yuan-Hao Chiang
  • 2,484
  • 9
  • 20