4

I have seen in react hook forms using as and also render

Eg:

    <Controller
      render={({ field }) => <input {...field} />}
      name="firstName"
      control={control}
      defaultValue=""
    />

or

    <Controller
      as={<input .. />}
      name="firstName"
      control={control}
      defaultValue=""
    />

whats the difference

Santhosh
  • 9,965
  • 20
  • 103
  • 243

1 Answers1

1

<Controller/> is good to use with there is an external controlled component such (e.g. Material-UI) to wrap the whole component and control is easier. render is useful when you want to customise the external component while as is just renders the original component. An example of using render could be:

import { TextField } from '@mui/material';
import { Controller } from 'react-hook-form';

const FormTextField = ({
  label,
  name,
  ...props
}) => {
  return (
      <Controller
        name={name}
        render={({ field, fieldState: { error } }) => (
          <TextField
            {...field}
            label={label}
            error={!!error}
            helperText={error ? error?.message : ''}
          />
        )}
        {...props}
      />
  );
};

As you can see, render gives you ability to access different values (such as error) in the Material UI component which is not easy to do with as.

Read more about what properties you have access in render at https://react-hook-form.com/api/usecontroller/controller

This example is also helpful: https://codesandbox.io/s/react-hook-form-v7-controller-5h1q5

Mehran
  • 96
  • 1
  • 2