react-hook-form with react select - reactjs

Someone has a working sample with a react-hook-form with a react-select? In below the Select with id="accountId" works. However I need it to be a required field. I tried adding:
innerRef={register({ required: true })}
But that did not work. AFAIK this is because the Select needs to be wrapped in a Controller (correct me if I am wrong).
So I tried adding the Controler where id="accountId2". But now I get error:
Uncaught TypeError: Cannot read property 'split' of undefined
I am looking for a small sample where the Select will be integrated with the form and required fields.
<Container>
<Form onSubmit={handleSubmit(onSubmit)}>
<FormGroup>
<div>
<Controller
as={<Select
name="accountId2"
id="accountId2" />}
options={options}
control={control}
/>
</div>
</FormGroup>
<FormGroup>
<Label for="exampleCheckbox">Choose account to update</Label>
<div>
<Select
name="accountId"
id="accountId"
innerRef={register({ required: true })}
isDisabled={isNewAccount}
ref={selectInputRef}
isClearable={true}
placeholder="Search for an existing account number or click new account below"
label="Single select"
options={options}
defaultValue=""
/>
</div>

Yes, In order for Select to work with RHF, you need to wrap it in a controller like this.
<Controller
as={
<Select>
{options.map((option, index) => (
<MenuItem key={index} value={option}>
{option}
</MenuItem>
))}
</Select>
}
name={options_name}
control={control}
defaultValue=""
rules={{ required: true }}
/>
So it worked for me by adding the following attribute to the controller.
rules={{ required: true }}
Hope this answers your question.

If you are using react-hook-form: "^7.19.1", can be used as below.
<Controller
control={control}
name="test"
render={({
field: { onChange, onBlur, value, name, ref },
fieldState: { invalid, isTouched, isDirty, error },
formState,
}) => (
<Select
onBlur={onBlur}
onChange={onChange}
inputRef={ref}
className={classes.textField}
fullWidth
input={<Input id="name" />}
defaultValue={"science"}
>
{tags.map((tag, index) => (
<MenuItem key={index} value={tag}>
{tag}
</MenuItem>
))}
</Select>
)}
/>

Related

React hooks form doesn't accept files, but string to system path instead

I'm trying to load a file using React hooks form and yup, but by wrapping the input type file component in Controller I get instead of the usual Blob, system paths like value
Example of result:
C:\\fakepath\\image.jpeg
Expected result
Blob file
Code example:
Link to sandbox: https://codesandbox.io/s/react-select-with-react-hook-form-forked-4t6ncr?file=/src/App.js
Code:
<form onSubmit={handleSubmit(saveData)}>
{!countryValue && (
<Controller
name="country"
control={control}
render={({ onChange, value, ref }) => (
<Select
options={country}
value={country.find((c) => c.value === value)}
onChange={(val) => onChange(val.value)}
/>
)}
rules={{ required: true }}
/>
)}
{countryValue && (
<Controller
name="country"
control={control}
render={(field) => {
const { onChange } = field;
return <input {...field} type="file" onChange={onChange} />;
}}
rules={{ required: true }}
/>
)}
{errors.country && <div>Field is rquired</div>}
<button type="submit">Save</button>
</form>

Password field showing "password is required" even after a value is passed

I am working on a login form with Next Js as frontend and uses MUI 5. The issue is that even after i pass a value to password field, when i click on login button it is showing password field is required. Also when i try to console log the username and password to test it, only username got displayed in the console. please help me to understand what mistake I am doing. Please find the login form below
Please find the code MUI code for both username and password(I am making use of a purchased theme)
<form noValidate autoComplete='off' onSubmit={handleSubmit}>
<FormControl fullWidth sx={{ mb: 4 }}>
<Controller
name='Username'
control={control}
rules={{ required: true }}
render={({ field: { value, onChange, onBlur } }) => (
<TextField
autoFocus
label='Username'
value={value}
onBlur={onBlur}
//onChange={onChange}
onChange={(e)=> setUsername(e.target.value)}
error={Boolean(errors.user)}
// placeholder='admin#materio.com'
/>
)}
/>
{errors.user && <FormHelperText sx={{ color: 'error.main' }}>{errors.user.message}</FormHelperText>}
</FormControl>
<FormControl fullWidth>
<InputLabel htmlFor='auth-login-v2-password' error={Boolean(errors.password)}>
Password
</InputLabel>
<Controller
name='password'
control={control}
rules={{ required: true }}
render={({ field: { value, onBlur } }) => (
<OutlinedInput
value={value}
onBlur={onBlur}
label='Password'
//onChange={onChange}
onChange={(e)=> setPassword(e.target.value)}
id='auth-login-v2-password'
error={Boolean(errors.password)}
type={showPassword ? 'text' : 'password'}
endAdornment={
<InputAdornment position='end'>
<IconButton
edge='end'
onMouseDown={e => e.preventDefault()}
onClick={() => setShowPassword(!showPassword)}
>
{showPassword ? <EyeOutline /> : <EyeOffOutline />}
</IconButton>
</InputAdornment>
}
/>
)}
/>
{errors.password && (
<FormHelperText sx={{ color: 'error.main' }} id=''>
{errors.password.message}
</FormHelperText>
)}
</FormControl>

Controller does not working for MUI Select and React Hook Form. TypeError: props.render is not a function

I have parent and child components. In the child component, I have a 'select' and 'textfield'. I need to configure validation for this select - "Required". Textfield works, but select does not. I could not do it and searched to solve this and saw "Controller". But when I send control (useForm) as a prop to my child component, the app does not work and my error is TypeError: props.render is not a function
Parent component:
const { register, handleSubmit, control, formState: { errors }} = useForm();
<AddProductInfo register={register} control={control} errors={errors} />
Child component:
<FormControl fullWidth>
<Typography variant={"span"} className={styles.select}>
Category
</Typography>
<Controller
as={
<Select
value={addProductData.category}
onChange={handleChange}
// {...register("category", {
// required: "Choose one of them",
// })}
// error={Boolean(errors.category)}
>
{categoriesData.map((data, key) => (
<MenuItem key={key} value={data.id}>
{data.name.az}
</MenuItem>
))}
</Select>
}
name={"category"}
control={control}
></Controller>
<FormHelperText error variant="filled">
{errors.category?.message}
</FormHelperText>
</FormControl>
I solved. The right code
from
<Controller as={
<Select>
</Select>
}
/>
to
<Controller render={({ field }) => (
<Select {...field}>
</Select>
)}
/>
Like this
<Controller
render={({ field }) => (
<Select
{...field}
>
{categoriesData.map((data, key) => (
<MenuItem key={key} value={data.id}>
{data.name.az}
</MenuItem>
))}
</Select>
)}
name={"category"}
control={control}
></Controller>

setValue not working for react hookform with select

I am using react hook form. setValue is not working with select.I tried both in controller and in function but that doesnt work.Below is my code.
<Controller
name="mealkit"
control={control}
register={register}
defaultValue="Ready to eat"
setValue={selectedRow.mealkit}
rules={{ required: true, minLength: 4 }}
render={({ field }) => (
<Select
defaultValue="Ready to eat"
setValue={selectedRow.mealkit}
variant="outlined"
fullWidth
id="mealkit"
label="Mealkit"
inputProps={{ type: 'mealkit' }}
error={Boolean(errors.mealkit)}
helperText={
errors.mealkit
? errors.mealkit.type === "minLength"
? "mealkit should have atleast 4 letters"
: "mealkit is required"
: ""
}
{...field}
>
<MenuItem value={'Ready to eat'}>Ready to eat</MenuItem>
<MenuItem value={'Ready to cook'}>Ready to cook</MenuItem>
<MenuItem value={'Heat and eat'}>Heat and eat</MenuItem>
</Select>
)}
/>

react-datepicker and react-hook-forms: required not working

React-datepicker and react-hook-form. I am trying to make react-datepicker required, but its not working
<Controller
name="resetDateTime"
control={control}
required
render={({ field }) => (
<Datetime
onChange={(date) => field.onChange(date)}
selected={field.value}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
viewMode="time"
/>
)}
/>
{errors.resetDateTime && <span>This field is required</span>}
When I submit form without selecting any datetime, I am expecting the error to be show, but instead it submits the form
<Controller /> has no required prop, instead of you have to pass the validation rules via the rules prop. Check the docs for more info.
<Controller
name="resetDateTime"
control={control}
rules={{ required: true }}
render={({ field }) => (
<Datetime
onChange={(date) => field.onChange(date)}
selected={field.value}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
viewMode="time"
/>
)}
/>
{errors.resetDateTime && <span>This field is required</span>}

Resources