react-final-form with autocomplite component

955 Views Asked by At

I have i dynamic form and having issue with Autocomplite component from material-ui when i connected with react-final-form-arrays, cant get the selected item value

here is form code

<Field
   name={`${name}`.product}
   list={products}
   component={AutocompleteField}
   label={'Products'}
/>
function ProductSelectField({list, label, dealer_id, stock_id, all_stocks, input, ...rest}) {

    const {name, onChange, ...restInput} = input;

    const [value, setValue] = useState([]);
    const [inputValue, setInputValue] = useState('');

    const getProducts = (event, newValue) => {
        setValue(newValue);
    }
    return (
        <Autocomplete
            {...rest}
            id="product"
            options={list}
            getOptionLabel={(option) => option.name}
            defaultValue={list[0]}
            onChange={getProducts}
            inputValue={inputValue}
            onInputChange={(event, newInputValue) => {
                setInputValue(newInputValue);
            }}
            renderInput={(params) =>
                <TextField
                    {...restInput}
                    {...params}
                    label={label}
                    variant="outlined"
                />
            }
        />
    );
}
1

There are 1 best solutions below

0
Tanner Priest On

Without any extra info or code box to go off of, it seems that you are not invoking the input's onChange hook to update the fields state. In your Autocomplete prop.onChange, you are invoking the getProducts hook but not where are you passing the value to the onChange hook.

- const {name, onChange, ...restInput} = input; //delete
     <TextField
       - {...restInput} //delete
         {...params}
         label={label}
         variant="outlined"
     />
// spread out the entire input prop into the Autocomplete
<Autocomplete
    {...input}
    {... rest of your props}
/>

These Docs on React-Final-Form shows you what the input prop passes down and it shows how it does all the work for you.

However, I use the Autocomplete from material-ui as well and understand you want to control the local state at the same time. Refactor your getProducts hook to update both.

const getProducts = (event, newValue) => {
        setValue(newValue);
        input.onChange(event); // the event will carry over because 'text' and 'select' inputs both return the 'event.target.value' without any extra logic for the Field component.
    }