Input form(markdown editer) lose foucs when state changed

Viewed 16

/// Component/MdEditor

import React, { useRef, useState, useCallback } from "react";
import "@uiw/react-md-editor/markdown-editor.css";
import "@uiw/react-markdown-preview/markdown.css";
import dynamic from "next/dynamic";

const MdEditor = () => {
/// config for next.js (disabling ssr)
  const MDEditor = dynamic(() => import("@uiw/react-md-editor"), {
    ssr: false,
  });

  const [md, setMd] = useState<string | undefined>("# Hello World");

  return <MDEditor value={md} onChange={setMd} />;
};

export default MdEditor;

/// index

...
return(
 /// some react hook form component///
  <div>
    <MdEditor />
  </div>

)

I'm using react md-editor(https://www.npmjs.com/package/@uiw/react-md-editor) at Next.js. Every time I input any character, it seems that 'MdEditor' Component is rerendered so that focus is lost. Also, when I moved the component to the parent component, the same problem happend again.

I just want to know the reason and solution for this situation.

Thank you.

1 Answers

This probably happen because you imported the module inside the function component. You can try to move the import to outside the function:

import React, { useRef, useState, useCallback } from "react";
import "@uiw/react-md-editor/markdown-editor.css";
import "@uiw/react-markdown-preview/markdown.css";
import dynamic from "next/dynamic";
const MDEditor = dynamic(() => import("@uiw/react-md-editor"), {
    ssr: false,
  });


const MdEditor = () => {
  const [md, setMd] = useState<string | undefined>("# Hello World");

  return <MDEditor value={md} onChange={setMd} />;
};

export default MdEditor;

Related