Home > other >  How to get a value from code mirror in react js?
How to get a value from code mirror in react js?

Time:06-17

I am trying to get a value from the code mirror input field but I don't know why I am not getting the value from code mirror input field

import CodeMirror from "@uiw/react-codemirror";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";

export default function Editor() {
    const [get, set] = useState("");
    console.log(get); {/* doesn't display anything */}
     
    return (
      <>
        <CodeMirror
          value={get}
          extensions={[
            markdown({ base: markdownLanguage, codeLanguages: languages }),
          ]}
          onInput={(e) => set(e.target.value)}
        />
      </>
    );
}

CodePudding user response:

The onChange handler can output the value as below.

import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";
import { useState } from "react";

export default function Editor() {
  const [get, set] = useState("");
  console.log(get);

  return (
    <>
      <CodeMirror
        value={get}
        extensions={[
          markdown({ base: markdownLanguage, codeLanguages: languages })
        ]}
        onChange={(value) => set(value)}
      />
    </>
  );
}

Working example

Edit dank-sun-dm1m8v

CodePudding user response:

Try useEffect hook, it calls the function inside whenever variable in second argument array changes, in this specific scenario when get changes.

import CodeMirror from "@uiw/react-codemirror";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { languages } from "@codemirror/language-data";
import { useEffect } from "react";

export default function Editor() {
    const [get, set] = useState("");
    
    useEffect(() => {
       console.log(get) //gets called whenever get state changes
    }, [get])
     
    return (
      <>
        <CodeMirror
          value={get}
          extensions={[
            markdown({ base: markdownLanguage, codeLanguages: languages }),
          ]}
          onInput={(e) => set(e.target.value)}
        />
      </>
    );
}
  • Related