I’m new to react and material UI and I’m trying to make a dropdown select component. I want to be able to pass onChange functions to the component from the parent, and I’ve followed the official documentation, but selecting the option doesn’t seem to do anything.
This is the child component:
export default function AutocompleteForm(props) {
const {label, array, handleSubmit} = props
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={array}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label={label}
onChange={handleSubmit} />}
/>
)
}
I pass it a label, an array of options to display and an onChange function.
In the parent, I have this:
const Form = () => {
const [value, setValue] = useState('')
const handleSelect = (event, newvalue) => {
console.log(newvalue)
setLabel(newvalue)
}
const options = ['Option 1', 'Option 2', 'Option 3']
return (
<AutocompleteForm array={options} label="Pick an option" handleSubmit={handleSelect}/>)
}
However, I don’t see the value from my handleSelect function displayed to the console, and the value is not updated either. I’m not sure what I’m doing wrong here, any tips would be appreciated!
2
Answers
I have changed some errors you have.
First don’t name a prop
function
since it is a reserved word, like the one you are using to create the componentsSecond your are closing the
renderInput
andTextfield
in theonChange
And third the
setLabel
I don’t know where it comes from it must be thesetValue
you have from the useState or you can rename the setValue for setLabelThis solution passes the onChange function to the Autocomplete component in the AutocompleteForm and provides parameters to it. The onChange function uses an event (event) and the new value (newValue) for its parameters in order to update the value in the parent component and log it to the console. This should make the dropdown select component fully functional.
Change name of function to "handleSelect"