Connecting Slate to Formik - is it useField?

643 views Asked by At

Here's the React component I'm creating to host Slate:

import React, { useMemo, useState } from "react";
import { Field, useField, ErrorMessage } from "formik";
import { Slate, Editable, withReact } from "slate-react";

const FormRichText = ({ label, ...props }) => {
  const [field, meta] = useField(props);
  const editor = useMemo(() => withReact(createEditor()), []);
  const [editorContent, setEditorContent] = useState(field.value);

  field.value = editorContent;

  return (
        <Slate
          {...field}
          {...props}
          name="transcript"
          editor={editor}
          onChange={(v) => setEditorContent(v)}
        >
          <Editable />
        </Slate>
  );
};

export default FormRichText;

The issue I'm having is when I try to connect it into Formik, whatever I edit will not pass to the Formik values in handleSubmit.

<FormRichText
     name="transcript"
     id="transcript"
/>

I don't understand Formik which is why I'm having the issue. I believe I need to surface the value of Slate (which I've stored in a state variable) but I'm struggling to work my way through Formik to know how to do that. I assumed that if I use the userField prop I would be able to set field.value and that would get through to Formik.

1

There are 1 answers

1
Rob On BEST ANSWER

This worked:

const FormRichText = ({ label, ...props }) => {
  const [field, meta, helpers] = useField(props.name);
  const editor = useMemo(() => withReact(createEditor()), []);

  const { value } = meta;
  const { setValue } = helpers;

  useEffect(() => {
    setValue([
      {
        type: "paragraph",
        children: [{ text: "Type something ..." }],
      },
    ]);
  }, []);

  return (
        <Slate name="transcript" 
          value={value} 
          editor={editor} 
          onChange={(v) => setValue(v)}>
          <Editable />
        </Slate>
      </div>
    </div>
  );
};

Hopefully this helps someone else.

Saying that, I still have to render content through Slate so I may be back on this thread!