Skip to content
Advertisement

Material-UI Select doesn’t update after onChange

I’ve seen this problem about all around the web but nothing could come short of giving me a valid explanation.

I’m using Material-UI Select and the good ol’ setState(…) from React (not hooks though)

My component is composed essentially of those lines :

class MyComponent extends Component {

exportOptions = ['CSV','SDF']

  constructor(props) {
    super(props);
    this.state = {
[...]
      formatToExportTo : this.exportOptions[0]
    };

[...]

<Select value={this.state.formatToExportTo}
        style={{width : "10em"}}
        onChange={event=> {
            this.setState({formatToExportTo : event.target.value})
        }}>{
            this.exportOptions.map(f=><MenuItem key={f} value={f}>{f}</MenuItem>)
        }</Select>,

And my problem is that my Select component dosen’t update its value after selecting another option.

So far I’ve tried :

  • setState({...this.state, formatToExport : event.target.value}) in the onChange= of the Select and in the Select tag : value = {this.state.formatToExport}
  • setState({...this.state, formatToExport : event.target.value}) in the onClick= of each options and in the Select tag : value = {this.state.formatToExport}. But that was only to see the update, because the event.target.value isn’t right anyway
  • and the current version of my lines written above also onClick OR onChange (without tthe cloning of state which is supposed to be done by setState alone).

It’s like in the official example so I truly don’t see where this lack of update could come from. No matter what I try, the currently displayed value of the Select component doesn’t change is display, even though the state was properly updated

Thank you for the time you took to read me !

Advertisement

Answer

After searching for 3 hours total :

normally value={this.state.formatToExportTo} should work ( I tried it alone without the rest of my app surrounding it) But since I made some quircky things with my this and the order of update, I just had to replace :

value={this.state.formatToExportTo} by defaultValue={this.state.formatToExportTo}

That’s all ! I hope it helps someone who’ll come by this question

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement