material-ui icon indicating copy to clipboard operation
material-ui copied to clipboard

If set value to TextField, can't change it anymore

Open Solitaryo opened this issue 10 years ago • 2 comments

Problem description

If you set a value in a TextField, by its property 'value', then, as a user you can't write on that TextField, for example: <TextField id={Math.random().toString()} ref={'usernameTf'} value={this.state.profile.username} /> I'm pretty sure you're asking to yourself, why use the value property and not the defaultValue, well, the point is defaultValue does not work when you use info from state.

Steps to reproduce

  1. Create a TextField.
  2. Put a value on it, using the property value.
  3. ???

Versions

  • Material-UI: 0.15.4
  • React: 15
  • Browser: Chrome 53, Opera 40.

Solitaryo avatar Oct 11 '16 19:10 Solitaryo

@Solitaryo: that's because <TextField /> only follows whatever is on the state.

To use state, you should provide an onChange() function prop so it changes the state value on user typing, something like:

<TextField
  value={this.state.myField.itsValue}
  onChange={(e) => this.setState({ myField: e.target.value })}
  ...
/>

A good tip is using something like formsy-react and its Material UI wrapper by @mbrookes.

lucasbento avatar Oct 11 '16 19:10 lucasbento

@Solitaryo You are controlling the component. That's the expected behavior. It's the same than with a native <input /> component. I'm closing this issue as it's linked with some core concept of React.

oliviertassinari avatar Oct 11 '16 19:10 oliviertassinari