Reputation: 175
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?
Upvotes: 0
Views: 3324
Reputation: 69
From Material UI documentation:
function(event: React.SyntheticEvent, value: T | Array<T>, reason: string, details?: string) => void
This is my onChange function from Grouped template with TypeScript:
onChange={(event, value, reason, details) => selectChangeHandler(event, value as { title: string, year: number, firstLetter: string }, reason, details)}
const selectChangeHandler = (event: SyntheticEvent, value: { title: string, year: number, firstLetter: string }, reason: string, details: unknown) => {
event.preventDefault()
console.log('value', value)
console.log('reason', reason)
console.log('details', details)
}
Upvotes: 0
Reputation: 7863
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>
);
}
}
Upvotes: 1