uiwjs / react-codemirror

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

is there any way to update CodeMirror value prop thru ref ? #392

Closed starc007 closed 2 years ago

starc007 commented 2 years ago

I want to dynamically update the value of CodeMirror. Is there any way using refs?

jaywcjlove commented 2 years ago
import React, { useState } from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

function App() {
  const [value, setValue] = useState('')
  const onChange = React.useCallback((value, viewUpdate) => {
    console.log('value:', value);
    setValue(value)
  }, []);
  return (
    <CodeMirror
      value={value}
      height="200px"
      extensions={[javascript({ jsx: true })]}
      onChange={onChange}
    />
  );
}

@starc007 Use state to change the value

https://github.com/uiwjs/react-codemirror/blob/b2341d3f8fb94345cbb759382870d81c61606812/core/src/index.tsx#L141-L146

It is also possible to use ref.

starc007 commented 2 years ago

in codemirror we have setValue() function to set value of codemirror dynamically, like this

editorRef.current.setValue(code);

in react-codemirror, is there something like this? I tried useState but it renders component everytime we update state.... so i am looking something like above code

jaywcjlove commented 2 years ago

@starc007

https://github.com/uiwjs/react-markdown-editor/blob/5ac54744b915b290ddde87da5f6f5bee96ee1e34/src/commands/code.tsx#L58-L67

editorRef.current.view.dispatch()
starc007 commented 2 years ago

Thanks @jaywcjlove