Simple react-hook-form with Material UI

·

1 min read

In last post I mentioned some differences between redux-form and react-hook-form.

In this post I will show you how to create simple form with Input name and email.

First, we will declare useForm()

const { register, handleSubmit, errors } = useForm();

and then create onSubmit function to handle form submit which will just console.log form inputs

const onSubmit = data => {
    console.log(data);
  };

Now let's create form, we use

to create form and have onSubmit method which we just created.

Next, we are using TextField from Material UI which is very straight forward. To make it compatible with react-hook-form use inputRef={register()} but in our case we are making it required.

To show error we will use errors from useForm and see if there is error then we will show helperText.

   <form onSubmit={handleSubmit(onSubmit)}>
        <Paper>
          <Typography variant="h4" gutterBottom>
            React-hook-form
          </Typography>
          <div>
            <TextField
              type="text"
              name="name"
              error={errors.name ? true : false}
              helperText={errors.name && `Name is mandatory`}
              id="name"
              label="Name"
              fullWidth
              inputRef={register({ required: true })}
            />
            <TextField
              error={errors.email ? true : false}
              name="email"
              helperText={errors.email && `Email is mandatory`}
              type="email"
              id="email"
              label="email"
              fullWidth
              inputRef={register({ required: true })}
            />
          </div>
          <Button
            className={classes.button}
            type="submit"
            color="primary"
            variant="contained"
          >
            Submit
          </Button>
        </Paper>
      </form>

Here is CodeSandbox to try it out.

Code Sandox