How to use uiw/react-codemirror as a react-hook-form field

267 Views Asked by At

I want to use CodeMirror editor as a field in a form that uses react-hook-form. Is there anyone who has done this before and how to register editor values using react hook form register method?

1

There are 1 best solutions below

0
Aditya Partole On

You can use the Controller component from react-hook-form to wrap your CodeMirror component. The Controller component is designed to work with uncontrolled components, like CodeMirror, that don’t expose an onChange event. You can use the Controller to handle events and updates between CodeMirror and react-hook-form.

like this-

import { useForm, Controller } from "react-hook-form";
import { UnControlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';

function YourComponent() {
  const { handleSubmit, control } = useForm();
  
  const onSubmit = (data) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        name="code"
        control={control}
        defaultValue=""
        render={({ field }) => (
          <CodeMirror
            {...field}
            options={{
              lineNumbers: true
            }}
            onChange={(editor, data, value) => {
              field.onChange(value);
            }}
          />
        )}
      />
      <input type="submit" />
    </form>
  );
}

Basically, Controller wraps the CodeMirror component and the onChange prop of CodeMirror is used to update the form value when the code in the editor changes.