react-markdown-editor-lite icon indicating copy to clipboard operation
react-markdown-editor-lite copied to clipboard

Editor loses focus when updating state

Open olaven opened this issue 5 years ago • 6 comments

Hi! We are looking into using this package for an application and it looks promising! Thanks! This may be due to an understanding, but we are having some issues.

Given the example below, these are the observations:

  • setting the state manually causes editor focus to be lost (i.e. have to click on editor again)
  • if manual state update is removed, it seems like the editor updates it automatically

In other words, the correct approach seems to be to just pass value and never handle the state. This is totally fine 👍 Great even, but not obvious (to me, at least).

However, loosing focus is still weird, as appears to be kept in the component.
Is this behaviour intended?

import React, { useState, useRef, useEffect } from 'react';
import dynamic from 'next/dynamic';
import MarkdownIt from 'markdown-it'
import 'react-markdown-editor-lite/lib/index.css';


export const SimpleMDEditor = () => {

    const [md, setMD] = useState("")

    const mdParser = new MarkdownIt();
    const MdEditor = dynamic(() => import('react-markdown-editor-lite'), {
        ssr: false
    });

    const handleEditorChange = ({ html, text }) => {

        console.log("text", text);
        //REMOVE LINE BELOW -> Focus is not lost 
        setMD(text);
    }

    return <MdEditor
        // key="markdownEditor"
        id="test"
        value={md}
        style={{ height: "500px" }}
        renderHTML={(text) => mdParser.render(text)}
        onChange={handleEditorChange}
    />
}

olaven avatar Jun 19 '20 20:06 olaven

What system and browser you are using?

sylingd avatar Jun 21 '20 10:06 sylingd

@sylingd Chrome/Firefox and the latest MacOS :-)

olaven avatar Jun 21 '20 10:06 olaven

@olaven I'm struggling with a similar issue, but not with this package. If the Editor is nested in another components, theres probably an issue with the rerendering. This and this might give some insight (I've not solved the issue myself yet).

If you figured it out, I would love some feedback/pointers! 😃

erlendoeien avatar Aug 07 '20 17:08 erlendoeien

Hi, @erlendoeien! Sorry for the late response. The solution was related to rerendering! I'm not entirely sure, but I think we ended up keeping the markdown-state in a parent. This was a collaboration effort and it's been a while, so I don't remember the details..

olaven avatar Aug 11 '20 08:08 olaven

If anyone bumbs with this issue, I was able to fix it by NOT using useState. I am currently declaring a variable outside the render function, and just updating that function. I am using Next.js as reference.

masaez avatar May 03 '21 22:05 masaez

@masaez hey masaez, could you share a code snippet of how you were able to solve this issue?

jaddoescad avatar Jun 15 '21 16:06 jaddoescad