Search code examples
reactjsreact-hooksmaterial-table

How to get set selected value inside TextField of AutoComplete Material UI


I have array of Object

const top100Films = [{ title: 'The Shawshank Redemption', year: 1994 },{ title: 'The Godfather', year: 
1972 },{ title: 'The Godfather: Part II', year: 1974 },{ title: 'The Dark Knight', year: 2008 },{ 
title: '12 Angry Men', year: 1957 }]

I'm using Autocomplete of Material UI

<Autocomplete
                // value={val}
                options={top100Films}
                getOptionLabel={option => option.title}
                style={{ width: 300 }}
                onChange={(event, value) => console.log(value)}
                renderInput={params => (
                    <TextField
                        {...params}
                        label="label"
                        variant="outlined"
                        fullWidth

                    />
                )}
            />

It just displays the value inside TextField but doesnot actually sets the value like

<input
        type="text"
        value={props.value}
        onChange={e => props.onChange(e.target.value)}
      /> 

This input sets the value.

I want to set the value inside Autofield's TextField not just display it. How can it be done? I have searched but I couldn't find any solution.

If anyone needs any further information please do let me know.


Solution

  • Please check its documentation where it is clearly mentioned:

    Signature: function(event: object, value: T | T[], reason: string) => void event: The event source of the callback. value: The new value of the component.

    here the first parameter is the event and second is the value.

    So you can get the selected value like:

    onChange={(event, selectedValue) => handleChange(selectedValue)}  // You can get the `selectedValue` inside your handler function on every time user select some new value