reactjsmaterial-uimui-autocomplete

Material-UI Autocomplete event.target


I use Autocomplete component and I have code like this:

const countries = [
    {country: 'Poland', code: 'PL'},
    {country: 'Germany', code: 'DE'},
    {country: 'Spain', code: 'ES'},
    {country: 'France', code: 'FR'}
]

const Input = ({onCountryChange}) => (
    <Autocomplete
    id="combo-box"
    options={countries}
    getOptionLabel={option => option.country}
    style={{ width: 300, marginTop: 10 }}
    onChange={onCountryChange}
    renderInput={params => (
      <TextField {...params} label="Type a country" variant="outlined" fullWidth />
    )}
    />
)
onCountryChange = (event) => {
    this.setState({
      countryCode: event.target.textContent
    });
  };

Now it sets as countryCode the country from countries options and I would like to use code instead (like PL). Any ideas how I can do this?


Solution

  • You have almost got the answer. I changed the onCountryChange function and look if this what you seek.

    here is a working example: https://codesandbox.io/s/brave-mccarthy-kqx97

    const countries = [
      { country: "Poland", code: "PL" },
      { country: "Germany", code: "DE" },
      { country: "Spain", code: "ES" },
      { country: "France", code: "FR" }
    ];
    
    class App extends React.Component {
      state = {
        countryCode: ""
      };
    
      onCountryChange = (object, value) => {
        this.setState({
          countryCode: value.code
        });
      };
    
      render() {
        const { countryCode } = this.state;
        return (
          <div className="App">
            {countryCode}
            <Autocomplete
              id="combo-box"
              options={countries}
              getOptionLabel={option => option.country}
              style={{ width: 300, marginTop: 10 }}
              onChange={this.onCountryChange}
              renderInput={params => (
                <TextField
                  {...params}
                  label="Type a country"
                  variant="outlined"
                  fullWidth
                />
              )}
            />
          </div>
        );
      }
    }