My goal is to trigger a custom function by the onChange event belonging to the child component, from the parent component. In my case the child component is the React MUI Autocomplete component.
Considering the example about the Controllable States from the documentation:
import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
const options = ['Option 1', 'Option 2'];
export default function ControllableStates() {
const [value, setValue] = React.useState(options[0]);
const [inputValue, setInputValue] = React.useState('');
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" />}
/>
</div>
);
}
as you can see, the onChange event is already defined to update the new value. Ok.
Usually, what I do to manipulate this event from the parent component is simply:
import * as React from 'react';
import ReactDOM from 'react-dom/client';
import { StyledEngineProvider } from '@mui/material/styles';
import Demo from './demo';
function handleChange(event)
{
console.log("Hello!")
}
ReactDOM.createRoot(document.querySelector("#root")).render(
<StyledEngineProvider injectFirst>
<Demo onChange={handleChange} />
</StyledEngineProvider>
);
But in this case it doesn't work, probably because onChange is "already taken" by the Autocomplete component.
Is there a workaround?