I use the following code to create a login page with form validation:
import React from 'react';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { useForm } from 'react-hook-form';
class SignIn extends React.Component {
const { register, handleSubmit, errors } = useForm();
const onSubmit = data => console.log(data);
console.log(errors);
render() {
return (
<div>
<Form onSubmit={handleSubmit(onSubmit)}>
<Label>Email : </Label>
<Input type="email" placeholder="email" name="email" ref={register({required: true, pattern: /^\S+@\S+$/i})}></Input>
<Label>Password : </Label>
<Input type="password" placeholder="password" name="password" ref={register({required: true, min: 8, maxLength: 20})}></Input>
</Form>
</div>
);
}
}
export default SignIn;
and I have a problem using react-hook-form inside the Class Component
My question, if it's possible, is: How to use the react-hook-form with Class Component without rewriting the code to the hook version?
You can't use hooks in react class components. The class that you provide looks small and I think that you can easily rewrite it to functional component. Perhaps you don't want to, you can provide hoc with useForm hook that wraps your class component.
export const withUseFormHook = (Component) => {
return props => {
const form = useForm();
return <Component {...props} {...form} />
}
}
And in you SignIn component simply do:
export default withUseFormHook(SignIn);
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