MUI RTE in a formik form, the cursor jumps to the start of the text field making the input typed backwards

159 Views Asked by At

I am using MUI Rich text Editor as a component, and using that component in a formik form. when i enter any text the cursor position is always at the beginning making it appear as the text is written backwards. here's the code snippet for Editor component

function Editor({
  onFocus,
  onChange,
  value,
  name,
  height,
  disabled,
  label,
  enlarge,
  setFieldValue,
  html,
}: {
  onFocus?: () => void;
  onChange?: (value: string | any) => void;
  setFieldValue: (name: string, value: string | any) => void;
  html?: boolean;
  enlarge?: boolean;
  disabled?: boolean;
  value: any;
  name: string;
  height?: number | string;
  label?: string;
}) {
const extractValue = (value: any): string | any => {
    let initialValue = null;
        if (value !== undefined && value !== null) {
          initialValue = convertToRaw(ContentState.createFromText(value));
        } else {
          initialValue = convertToRaw(ContentState.createFromText(''));
        }
    return JSON.stringify(initialValue);
  };
 const [initialValue, setInitialValue] = useState<any>(extractValue(value));
 const editorRef: any = useRef(null);
const performChange = async (newValue: any) => {
    if (onChange !== null && onChange !== undefined && value !== newValue) {
      onChange(newValue);
    }
    if (setFieldValue !== null && setFieldValue !== undefined && value !== newValue) {
      setFieldValue(name, newValue);
    }
  };

  const handleChange = (event: any) => {
    if (html === true) {
      const newValueHTML = stateToHTML(event.getCurrentContent());
      performChange(newValueHTML);
    } else {
      const newValue = JSON.stringify(convertToRaw(event.getCurrentContent()));
      setInitialValue(newValue);
      performChange(newValue);
    }
  };
  const MUIEditor = (
    <>
      <ThemeProvider theme={defaultTheme}>
        <MUIRichTextEditor
          ref={editorRef}
          onFocus={focus}
          defaultValue={initialValue}
          onChange={handleChange}
          inlineToolbar={disabled ? false : true}
          label={disabled ? '' : label}
          toolbarButtonSize="small"
          toolbar={disabled ? false : true}
          readOnly={disabled ? true : false}
        />
      </ThemeProvider>
    </>
  );

  

here's the code snippet for my formik form

<Formik>{({ isValid, handleSubmit, dirty, values, setFieldValue, setFieldTouched, touched }: any) => (
<Form>
<Editor
 onFocus={() => {
 if (values.description !== undefined) {setFieldTouched('description', true, true);}}}
 setFieldValue={(name, value) => setFieldValue(name, value)}
 height={150}
 value={values.description}
 name="description"
 enlarge={true}
 disabled={values.disabled === true}
 label={description}
></Editor>
</form>
</Formik>

cursor should move ahead as per input

0

There are 0 best solutions below