Mehdi Faraji
Mehdi Faraji

Reputation: 3854

How can I submit the value of an autocomplete from material ui?

I've installed material ui and I'm getting autocomplete options from jsonplaceholder and It works pretty fine and this is my code :

    const [ value, setValue ] = useState([]);
    const [ inputValue, setInputValue ] = useState('');
    useEffect(() => {
        axios
            .get('https://jsonplaceholder.typicode.com/posts')
            .then((res) => {
                setValue(res.data);
            })
            .catch((e) => {
                console.log('error happened');
            });
    }, []);

            <Autocomplete
                id="combo-box-demo"
                options={value}
                getOptionLabel={(option) => option.title}
                style={{ width: 300 }}
                inputValue={inputValue}
                onInputChange={(event, newInputValue) => {
                    setInputValue(newInputValue);
                }}
                onSubmit={() => console.log('hey')}
                renderInput={(params) => (
                    <TextField 
                   onSubmit={() => console.log('hh')}
                   {...params} 
                 label="Combo box" variant="outlined" />


Now the thing I want to achieve is when user selects an option , I want to console log something . I did try onSubmit on Textfield but it doesn't work .

How can I console log when the users selects an option from autocomplete or presses enter on the textfield ?

Upvotes: 1

Views: 6826

Answers (1)

technicallynick
technicallynick

Reputation: 1592

As per the documentation, onChange needs to replace your onSubmit attribute on the Autocomplete component. This will fire whenever a user has selected a new option from the dropdown that is generated. If your Autocomplete were also a "freeSolo" field, it would NOT work when something were simply typed in and the user were to hit 'Enter'.

https://material-ui.com/api/autocomplete/

Upvotes: 2

Related Questions