Search code examples
reactjsweb-componentmaterial-ui

React and setState and autocomplete


Im using react and material ui. This is my component

```

import React from 'react';


import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';

import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AutoComplete from 'material-ui/AutoComplete';
// the light theme
const lightMuiTheme = getMuiTheme(lightBaseTheme);

// the autocomplete component width
const Preferencestypeahead = {
maxWidth: 600,
position:'relative',
margin:'auto'
}


export default class Preferences extends React.Component {


constructor(props) {
super(props);
this.handleUpdateInput = this.handleUpdateInput.bind();
this.state = {
  dataSource: [],
};
}

handleUpdateInput(value){
this.setState({
  dataSource: [
    value,
    value + value,
    value + value + value,
  ],
});
};

render() {
return (


    <div>
        <MuiThemeProvider muiTheme={lightMuiTheme}> 

                    <section style={Preferencestypeahead}>
                            <AutoComplete
                              hintText="Type"
                              dataSource={this.state.dataSource}
                              onUpdateInput={this.handleUpdateInput.bind(this)}
                              floatingLabelText="Search"
                              fullWidth={true}
                            />                          
                    </section>

        </MuiThemeProvider>
    </div>

    )

   }
  }

I keep getting setState is not defined when I type anything inside the autocomplete. Where could I be going wrong? I have also faced this problem when I tried to import the tabs as well


Solution

  • You need to bind to "this"

    This line is the problem:

    this.handleUpdateInput = this.handleUpdateInput.bind();
    

    Change it to:

    this.handleUpdateInput = this.handleUpdateInput.bind(this);