setValue not working for react hookform with select - reactjs

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>
)}
/>

Related

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>

next js state change doesnt change value of input

I have this piece of code but that does not change value of input field when state changes.State changes when user clicks on a row. State is changing as i printed the value outside text field but that does not reflect in input field. I tried with value instead of defaultValue but it doesnt work.
<Controller
name="name"
control={control}
defaultValue={selectedRow.name}
value={selectedRow.name}
rules={{
required: true,
}}
render={({ field }) => (
<TextField
variant="outlined"
fullWidth
id="name"
label="Name"
error={Boolean(errors.name)}
helperText={
errors.name ? 'Name is required' : ''
}
{...field}
></TextField>
)}
></Controller>
It looks like you use react-hook-from (https://react-hook-form.com/).
value and onChange should be inside of TextField like this.
<Controller
name="name"
control={control}
rules={{
required: true,
}}
render={({ field, value, onChange }) => (
<TextField
value={value}
onChange={onChange}
variant="outlined"
fullWidth
id="name"
label="Name"
error={Boolean(errors.name)}
helperText={
errors.name ? 'Name is required' : ''
}
{...field}>
</TextField>
)}
/>

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>}

react-hook-form, error when using for data update

I am trying to configure a react-hook-form to work for create and update operations. I am using material ui autocomplete and textfield.
The problem I am facing is with a field that has autocomplete.
If I pass an input value, it displays it, but when the form is submitted, the required error is triggered (as if the field has not been filled in).
This is my code:
<Controller
control={control}
name="type"
render={({ field: { onChange, value }, fieldState: { error } }) => (
<Autocomplete
value={value}
onChange={(event, item) => {
onChange(item.value);
}}
id="type"
defaultValue={props.operation === 'edit' ? props.values.type : null}
options={projectTypes}
renderInput={(params) => <TextField {...params}
error={!!error}
helperText={error ? error.message : null}
label="type"
{...register('type')}
/>}
/>
)}
rules={{ required: 'Project type is required' }}
/>
I have tried to add the input value as "inputValue", but then my options, are not available and I cannot either clear the value from the field.
Any ideas on what is wrong here?
The problem is you're using both <Controller /> and register to register your field.
You should only use one of them, in your use case you should use <Controller /> and get rid of the register call inside your <TextField />.
You should also pass the defaultValue for your field to <Controller /> instead of passing it to <Autocomplete />.
<Controller
control={control}
name="type"
defaultValue={props.operation === 'edit' ? props.values.type : null}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<Autocomplete
value={value}
onChange={(event, item) => {
onChange(item.value);
}}
id="type"
options={projectTypes}
renderInput={(params) => (
<TextField
{...params}
error={!!error}
helperText={error ? error.message : null}
label="type"
/>
)}
/>
)}
rules={{ required: 'Project type is required' }}
/>

react-hook-form with react select

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>
)}
/>

Resources