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

1.4k views Asked by At

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)}
        />
      </>
    );
}
2

There are 2 answers

2
Amila Senadheera On BEST ANSWER

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

4
rastiq On

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)}
        />
      </>
    );
}