uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.61k stars 128 forks source link

Changing value of code editor #499

Open pawan-poudel-github opened 1 year ago

pawan-poudel-github commented 1 year ago

I have searched a lot but didn't found a simple question answer and comes here for creating issue, How to change value of editor when some button is clicked or I mean dynamically without using state.

jaywcjlove commented 1 year ago

@pawan-poudel-github https://codesandbox.io/embed/react-codemirror-example-codemirror-6-https-github-com-uiwjs-react-codemirror-issues-499-8q9j79?fontsize=14&hidenavigation=1&theme=dark

I'm not sure about your needs. I don't know if the above example can solve your problem.

pawan-poudel-github commented 1 year ago

@pawan-poudel-github https://codesandbox.io/embed/react-codemirror-example-codemirror-6-https-github-com-uiwjs-react-codemirror-issues-499-8q9j79?fontsize=14&hidenavigation=1&theme=dark

I'm not sure about your needs. I don't know if the above example can solve your problem.

You are right, but I don't want that value of codemirror to be store on state

jaywcjlove commented 1 year ago

@pawan-poudel-github you want to use ref?

pawan-poudel-github commented 1 year ago

@pawan-poudel-github you want to use ref?

Yes I am saying something like of actual codemirror like EditorRef.current.setValue("int a =5")

jaywcjlove commented 1 year ago

@pawan-poudel-github https://codesandbox.io/embed/react-codemirror-example-codemirror-6-https-github-com-uiwjs-react-codemirror-issues-499-8q9j79?fontsize=14&hidenavigation=1&theme=dark

import React, { useRef, useState } from "react";
import CodeMirror from "@uiw/react-codemirror";
import { javascript } from "@codemirror/lang-javascript";

export default function App() {
  const $edit = useRef();
  const [val, setVal] = useState("console.log('hello world!');");
  const onChange = React.useCallback((value, viewUpdate) => {
    console.log("value:", value);
  }, []);
  const onRefChange = () => {
    $edit.current.view.dispatch({
      changes: { from: 0, to: 12, insert: "test" + new Date() }
    });
  };
  return (
    <div>
      <button onClick={() => setVal("Time: " + new Date())}>
        Change Value
      </button>
      <button onClick={onRefChange}>Ref Change Value</button>
      <CodeMirror
        value={val}
        ref={$edit}
        height="200px"
        theme="dark"
        extensions={[javascript({ jsx: true })]}
        onChange={onChange}
      />
    </div>
  );
}