I am trying to figure out onChange event using react hook form controller for materialui select but I cannot figure out how to trigger the event when select changes to call handleChange event. I have created a sandbox to replicate where I also have separate issue of Warning: findDOMNode is deprecated in StrictMode
which I can't get my head around how to use the createRef to stop this but the main problem is onChange event as I need to render different further TextFields based off the Select-value.
https://codesandbox.io/s/react-hook-form-select-onchange-uiic6
<form onSubmit={handleSubmit(onSubmit)}>
<Grid container direction="column" spacing={2}>
<Grid item>
<FormControl fullWidth variant="outlined" className={classes.formControl}>
<InputLabel id="demo-simple-select-label">Folder Name</InputLabel>
<Controller
control={control}
name="folderSelect"
onChange={handleChange}
defaultValue=""
render={({onChange, value, onBlur, name}) => (
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
onChange={onChange}
value={value ? value : ''}
name={name}>
<MenuItem value="Invoices" key="Invoices">
Invoices
</MenuItem>
<MenuItem value="Statements" key="Statements">
Statements
</MenuItem>
<MenuItem value="Credits" key="Credits">
Credits
</MenuItem>
</Select>
)}
/>
</FormControl>
</Grid>
<Grid item>
<TextField
fullWidth
label="First Name"
name="firstName"
variant="outlined"
onChange={(e) => console.log(e.target.value)}
inputRef={register({required: true})}
/>
</Grid>
<Button type="submit">Submit</Button>
</Grid>
</form>;
React Hook Form is focusing on uncontrolled inputs, which means you don't need to change the input value via state via onChange . This means you don't need value at all, and in fact, you only need to set defaultValue for the initial input value.
=> ({ onChange, onBlur, name, ref }) This method allows you to register an input or select element and apply validation rules to React Hook Form. Validation rules are all based on the HTML standard and also allow for custom validation methods.
There is no onChange
method for Controller
as you defined in your code. So you can remove it this:
<Controller
control={control}
name="folderSelect"
onChange={() => console.log("hellow")} <- this one not required
defaultValue=""
What I understand for your question you want to trigger handleChange
as soon as select
value updated. For this you can do this:
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
onChange={(e) => {
onChange(e)
handleChange(e) <- call handleChange
}}
value={value ? value : ""}
name={name}
>
Here is code and demo: https://codesandbox.io/s/react-hook-form-select-onchange-forked-eqb20?file=/src/App.js:1533-1907
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With