Is it possible to use react-datepicker with react hooks forms? - reactjs

Is it possible to use react-datepicker with react hooks forms? I tried following sample:
https://codesandbox.io/s/awesome-shape-j0747?fontsize=14&hidenavigation=1&theme=dark
But with no luck.
import React, { useState } from "react";
import "./styles.css";
import { useForm } from "react-hook-form";
import { Row, Col, Form, FormGroup, Label, Input, Button } from "reactstrap";
import DatePicker from "react-datepicker";
export default function App() {
const { register, handleSubmit } = useForm();
const [startDate, setStartDate] = useState();
const [result, setResult] = useState();
const onSearch = event => {
setResult(event);
};
return (
<div className="App">
<Form onSubmit={handleSubmit(onSearch)}>
<Row>
<Col>
<FormGroup>
<Input
type="number"
name="account"
id="account"
placeholder="AccountId"
innerRef={register({ required: true, maxLength: 20 })}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col>
<DatePicker
innerRef={register}
name="datetime"
className={"form-control"}
selected={startDate}
onChange={date => setStartDate(date)}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="MM-dd-yyyy h:mm"
/>
</Col>
</Row>
<Button>Submit</Button>
</Form>
<div>{JSON.stringify(result)}</div>
</div>
);
}

Please take a look at the Controller doc: https://react-hook-form.com/api/#Controller
which we are maintaining a codesandbox example for hosting most the external components UI libs' implementations: https://codesandbox.io/s/react-hook-form-controller-079xx
<Controller
as={ReactDatePicker}
control={control}
valueName="selected" // DateSelect value's name is selected
onChange={([selected]) => selected}
name="ReactDatepicker"
className="input"
placeholderText="Select date"
/>
EDIT
with the latest version of react-hook-form this is the Controller implementation using render:
<Controller
name={name}
control={control}
render={({ onChange, value }) => (
<DatePicker
selected={value}
onChange={onChange}
/>
)}
/>

With react-hooks-form v7
import dependencies:
import { Controller, useForm } from 'react-hook-form'
import DatePicker from 'react-datepicker'
add control to the useForm() hook:
const { control, register, handleSubmit, ... } = useForm()
Add the Controller and DatePicker component:
<Controller
control={control}
name='date-input'
render={({ field }) => (
<DatePicker
placeholderText='Select date'
onChange={(date) => field.onChange(date)}
selected={field.value}
/>
)}
/>

Related

Input value is showing undefined (reading 'value') while using rsuite library

It is basically rsuite#4.10.2 version
const [user, setuser] = useState('')
<InputGroup>
<Input type='text' value={user} onChange={e=>{setuser(e.target.value)}} id="user"/>
<InputGroup.Button>
<Icon icon="user" />
</InputGroup.Button>
</InputGroup>
also i have provided with the error image just look this out
enter image description here
rsuite library return the value directly in the onChange function.
So, instead:
onChange={e=>{setuser(e.target.value)}}
You should write
onChange={value=>{setuser(value)}}
This is a class that I have written with rsuite / bootstrap and basic input. You can see the difference and copy/paste the part that you want.
import React, { useState } from 'react';
import { InputGroup, Input } from 'rsuite';
import InputGroupBoostrap from 'react-bootstrap/InputGroup';
import FormControlBoostrap from 'react-bootstrap/FormControl';
const Question2 = () => {
const [user, setUser] = useState('example');
return (
<>
{/* rsuite */}
<InputGroupBoostrap>
<Input type='text' value={user} onChange={value=>{ setUser(value)}} id="user"/>
<InputGroup.Button>
Button
</InputGroup.Button>
{/* Bootstrap */}
</InputGroupBoostrap>
<InputGroupBoostrap>
<InputGroupBoostrap.Text>User 1</InputGroupBoostrap.Text>
<FormControlBoostrap value={user} onChange={(e) => { setUser(e.target.value); }} placeholder="user" />
</InputGroupBoostrap>
{/* input */}
<div>
<span>User 2</span>
<input value={user} onChange={(e) => { setUser(e.target.value); }}/>
</div>
</>
);
}
export default Question2;
I hope I've helped

How can I use useForm's register with dynamic parameter?

I want to create a form by using react-hook-form, but I am having trouble with it. As I found, there was a big change at v7 so the code I used as a reference is not working. I tried to modify it, and I figured out the problem is with the registering, but I cannot pass that name parameter dynamically.
My main component.
import React from 'react';
import i18next from 'i18next';
import { Button, Grid, Typography } from '#material-ui/core';
import { useForm, FormProvider } from 'react-hook-form';
import { Link } from 'react-router-dom';
import FormInput from './CustomTextField'
const AddressForm = ({ next }) => {
const methods = useForm();
return (
<>
<Typography variant="h6" gutterBottom>
{i18next.t('shipping_address')}
</Typography>
<FormProvider {...methods}>
<form onSubmit={methods.handleSubmit((data) => {
console.log(data);
next({ ...data })})}>
<Grid container spacing={3}>
<FormInput required register={methods.register} name='lastName' label={i18next.t('last_name')} />
<FormInput required register={methods.register} name='firstName' label={i18next.t('first_name')} />
<FormInput required register={methods.register} name='email' label={i18next.t('mail')} />
<FormInput required register={methods.register} name='zip' label={i18next.t('zip_code')} />
<FormInput required register={methods.register} name='city' label={i18next.t('city')} />
<FormInput required register={methods.register} name='address1' label={i18next.t('address_1')} />
</Grid>
<br />
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Button component={Link} to="/cart" variant="outlined">
{i18next.t('back_to_cart')}
</Button>
<Button type="submit" variant="contained" color="primary">
{i18next.t('next_step')}
</Button>
</div>
</form>
</FormProvider>
</>
)
}
export default AddressForm
CustomTextField component:
import React from 'react';
import { TextField, Grid } from '#material-ui/core';
import { useFormContext, Controller } from 'react-hook-form';
const CustomTextField = ({ name, label, register, required}) => {
const { control } = useFormContext();
return (
<Grid item xs={12} sm={6}>
<Controller
control={control}
name={name}
render = {(field) => (
<TextField
{...register({name})} // <--- It is not working like this
label={label}
required={required}
/>
)}
/>
</Grid>
)
}
export default CustomTextField
By the doc: https://react-hook-form.com/api/useform/register
it takes the input field's name as a parameter, if I pass it in as a string, it works fine. How can I pass the name's value as a parameter to the register() function?
The problem is you're mixing RHF's <Controller /> and register. As Mui's <TextField /> is an external controlled component you should use <Controller />. Check the docs here for more info.
const CustomTextField = ({ name, label, register, required}) => {
const { control } = useFormContext();
return (
<Grid item xs={12} sm={6}>
<Controller
control={control}
name={name}
render={({ field: { ref, ...field } }) => (
<TextField
{...field}
inputRef={ref}
label={label}
required={required}
/>
)}
/>
</Grid>
)
}
If you really want to use register here, you have to remove the wrapping <Controller /> and pass a name as a string instead as an object like you are doing right now. But i would recommend to use <Controller /> as with register you are losing the functionality of setting up the correct ref for your <TextField /> input element as it is linked via the inputRef prop instead of using ref which RHF register uses.
const CustomTextField = ({ name, label, register, required}) => {
const { control } = useFormContext();
return (
<Grid item xs={12} sm={6}>
<TextField
{...register(name)}
label={label}
required={required}
/>
</Grid>
)
}

Console Log from Props

I'm confused as I have managed to get my data to be logged via different means, but confused as to why when I use props for the data (rather than repeating code) it will not log the input.
For reference, I have a field component that will take props to drive what my react-hook-form TextField will request. I'd like to expand on the component but until it logs my data, I cannot proceed!
Below is the code that actually logs my data:
import React from "react";
import { useForm, Controller } from "react-hook-form";
import { TextField, Button } from "#material-ui/core/";
const NewRequest = () => {
const { register, handleSubmit, control } = useForm();
const onSubmit = (data) => console.log(data);
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
control={control}
name='firstName'
render={({ field: { onChange, onBlur, value, name, ref } }) => (
<TextField
label='First Name'
variant='filled'
size='small'
onBlur={onBlur}
onChange={onChange}
checked={value}
inputRef={ref}
/>
)}
/>
<br />
<br />
<Button type='submit' variant='contained'>
Submit
</Button>
</form>
</div>
);
};
export default NewRequest;
I have then moved the Controller, TextField to create a component:
import React from "react";
import { Controller, useForm } from "react-hook-form";
import { TextField } from "#material-ui/core/";
const TextFieldComponent = (props) => {
const { name, label, size, variant } = props;
const { control } = useForm();
return (
<div>
<Controller
control={control}
name={name}
render={({ field: { onChange, onBlur, value, ref } }) => (
<TextField
label={label}
variant={variant}
size={size}
onBlur={onBlur}
onChange={onChange}
checked={value}
inputRef={ref}
/>
)}
/>
</div>
);
};
export default TextFieldComponent;
Which I am using inside of another component (to generate a full form) and passing through my props (I will make a different component for Button, but for now it is where it is):
import React from "react";
import { useForm, Controller } from "react-hook-form";
import TextFieldComponent from "./form-components/text-field";
import { Button } from "#material-ui/core/";
const NewRequest= () => {
return (
<div>
<TextFieldComponent
name='firstName'
label='First Name'
size='small'
variant='filled'
/>
<br />
<br />
<Button type='submit' variant='contained'>
Submit
</Button>
</div>
);
};
export default NewRequest;
Now pushing that component into an index.js file to render a form:
import React from "react";
import NewVendorForm from "../components/new-vendor-request";
import { useForm } from "react-hook-form";
const Home = () => {
const { handleSubmit } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<NewVendorForm />
</form>
);
};
export default Home;
I'm stumped as to why this way would
a) customise my TextField in my form as intended
b) but not log my data as requested
I'm sure there is a very valid, basic reason as to why and it is my lack of understanding of console logging, but am in need of help to resolve!
Many thanks in advance.
The issue is that, in the refactored code, you're calling useForm twice, each of which generates a different control and data. You probably want to call useForm at the top level only, and pass in whatever you need (in particular control) to the form fields.
const Home = () => {
const { handleSubmit, control } = useForm();
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<NewVendorForm control={control} />
</form>
);
};
const NewRequest= ({control}) => {
return (
<div>
<TextFieldComponent
name='firstName'
label='First Name'
size='small'
variant='filled'
control={control}
/>
<br />
<br />
<Button type='submit' variant='contained'>
Submit
</Button>
</div>
);
};
const TextFieldComponent = (props) => {
const { name, label, size, variant, control } = props;
return (
<div>
<Controller
control={control}
name={name}
render={({ field: { onChange, onBlur, value, ref } }) => (
<TextField
label={label}
variant={variant}
size={size}
onBlur={onBlur}
onChange={onChange}
checked={value}
inputRef={ref}
/>
)}
/>
</div>
);
};

Using <TextField /> component from material-ui with react-hook-form shows warning

I am using react-hook-form for form state management in my application. When I am using <Input /> as a control, it works as expected, however with <TextField /> it shows a warning saying "A component is changing an uncontrolled input of type text to be controlled."
What's going wrong here? Is there any alternative for this component?
Here is my react code:
import React from "react";
import "./styles.css";
import { useForm, Controller } from "react-hook-form";
import Joi from "#hapi/joi";
import { TextField, createMuiTheme, ThemeProvider } from "#material-ui/core";
const validationSchema = Joi.object({
username: Joi.string()
.alphanum()
.min(3)
.max(30)
.required()
});
const theme = createMuiTheme({
palette: {
type: "dark"
}
});
const resolver = (data, validationContext) => {
const { error, value: values } = validationSchema.validate(data, {
abortEarly: false
});
return {
values: error ? {} : values,
errors: error
? error.details.reduce((previous, currentError) => {
return {
...previous,
[currentError.path[0]]: currentError
};
}, {})
: {}
};
};
export default function App() {
const { register, handleSubmit, errors, control } = useForm({
validationResolver: resolver,
validationContext: { test: "test" }
});
console.log("error", errors);
return (
<ThemeProvider theme={theme}>
<div className="App">
<h1>Hello CodeSandbox</h1>
<form onSubmit={handleSubmit(d => console.log(d))}>
<label>Username</label>
<Controller as={<input />} name="username" control={control} />
<Controller
as={<TextField />}
name="firstName"
label="First Name"
control={control}
/>
<input type="submit" />
</form>
</div>
</ThemeProvider>
);
}
and here is a link to it in a sandbox: https://codesandbox.io/s/react-hook-form-validationresolver-7k33n
You can fix the warning by supplying default values to your input elements to prevent them from being undefined initially:
<Controller
as={<input />}
name="username"
control={control}
defaultValue=""
/>
<Controller
as={<TextField />}
name="firstName"
label="First Name"
control={control}
defaultValue=""
/>

react-hook-form reset is not working with Controller + antd

I'm trying to use react-hook-form together with the antd <Input /> component
I'm not getting reset to work with <Controller />
Here is my code:
const NormalLoginForm = () =>{
const {reset, handleSubmit, control} = useForm();
const onSubmit = handleSubmit(async ({username, password}) => {
console.log(username, password);
reset();
});
return (
<form onSubmit={onSubmit} className="login-form">
<Form.Item>
<Controller as={<Input
prefix={<Icon type="user" style={{color: 'rgba(0,0,0,.25)'}}/>}
autoFocus={true}
placeholder="Benutzername"
/>} name={'username'} control={control}/>
</Form.Item>
<Form.Item>
<Controller as={<Input
prefix={<Icon type="lock" style={{color: 'rgba(0,0,0,.25)'}}/>}
type="password"
placeholder="Passwort"
/>} name={'password'} control={control}/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="login-form-button">
Log in
</Button>
</Form.Item>
</form>
);
}
I'm expecting that the two input fields are getting cleared when the form is submitted. But that doesn't work.
Am I missing something here?
Example on Stackblitz
https://stackblitz.com/edit/react-y94jpf?file=index.js
Edit:
The RHFInput mentioned here React Hook Form with AntD Styling is now part of react-hook-form and has been renamed to Controller. I'm already using it.
I've figured out that chaning
reset();
to
reset({
username:'',
password:''
});
solves the problem.
However - I wanted to reset the whole form without explicitly assigning new values.
Edit 2:
Bill has pointed out in the comments that it's almost impossible to detect the default values for external controlled inputs. Therefore we're forced to pass the default values to the reset method. That makes totally sense to me.
You must wrapper the components for antd and create a render component, it is very similar if you use Material UI, So the code can be like:
import { Input, Button } from 'antd';
import React from 'react';
import 'antd/dist/antd.css';
import {useForm, Controller} from 'react-hook-form';
const RenderInput = ({
field: {
onChange,
value
},
prefix,
autoFocus,
placeholder
}) => {
return (
<Input
prefix={prefix}
autoFocus={autoFocus}
placeholder={placeholder}
onChange={onChange}
value={value}
/>
);
}
export const NormalLoginForm = () =>{
const {reset, handleSubmit, control} = useForm();
const onSubmit = ({username, password}) => {
console.log(username, password);
reset();
};
return (
<form onSubmit={handleSubmit(onSubmit)} className="login-form">
<Controller
control={control}
name={'username'}
defaultValue=""
render={ ({field}) => (
<RenderInput
field={field}
autoFocus={true}
placeholder="Benutzername"
/>
)}
/>
<Controller
render={ ({field}) => (
<RenderInput
field={field}
type="password"
placeholder="Passwort"
/>
)}
defaultValue=""
name={'password'}
control={control}
/>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
>
Log in
</Button>
</form>
);
}
export default NormalLoginForm;
You can notice that I did't put the Icon ,it was because I tested using the version 4 for antd and something change in how to use the icons.

Resources