I am trying to get a very simple react app up-and-running.
The use case is straightforwards: An auto-complete component that gets an array of account names, and upon value changed (user has selected the value) - fire event that will display the account.
Here is a code snippet, which I am trying to get work in a way that showAccount method will have access to App's state.
How can I access App's state from showAccount()
?
import React, { Component } from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import AutoComplete from 'material-ui/AutoComplete';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
import './App.css';
class App extends Component {
constructor () {
super();
this.state = {accounts: []}
}
componentDidMount() {
this.setState({ accounts: [
{account_name: "foo", account_id: 1},
{account_name: "bar", account_id: 2}
]})
}
showAccount (value) {
// HERE IS THE PROBLEM!
// `this` points to AutoComplete rather than to App
console.log(this.state.accounts)
}
render() {
return (
<MuiThemeProvider>
<div className="App">
<center>
<AutoComplete
floatingLabelText="account name"
filter={AutoComplete.caseInsensitiveFilter}
dataSource={this.state.accounts.map((account) => account.account_name)}
onUpdateInput={this.showAccount}
/></center>
</div>
</MuiThemeProvider>
);
}
}
export default App;