Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use react-hook-form inside class Component?

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?

like image 842
Youness Saadna Avatar asked Sep 02 '26 22:09

Youness Saadna


1 Answers

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);
like image 173
piotrruss Avatar answered Sep 04 '26 14:09

piotrruss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!