react-live icon indicating copy to clipboard operation
react-live copied to clipboard

codemirror withlive

Open mickeygray opened this issue 5 years ago • 1 comments

hi I am look for examples on how to pass withlive into a textarea. I am rendering react html email to html and i would like to be able to interact with what is being produced in LivePreview. Is this doable with withlive and if so... how?

mickeygray avatar Jun 14 '20 06:06 mickeygray

@mickeygray if you are using the standard LiveProvider:

  <LiveProvider code="<strong>Hello World!</strong>">
    <LiveEditor />
    <LiveError />
    <LivePreview />
  </LiveProvider>

Then you can use this as a drop in replacement for LiveEditor:

import { javascript } from "@codemirror/lang-javascript";
import { dracula } from "@uiw/codemirror-theme-dracula";
import ReactCodeMirror from "@uiw/react-codemirror";
import { useContext, useMemo } from "react";
import { LiveContext } from "react-live";

export default function CodeEditor() {
  //@ts-ignore - onChange doesn't seem to be in the context types!
  const { code, language, theme, disabled, onChange } = useContext(LiveContext);

  const extensions = useMemo(() => {
    // you can add as many cases as you might have
    switch (language) {
      default:
        return [javascript({ jsx: true })];
    }
  }, [language]);

  const codeMirrorTheme = useMemo(() => {
    // you can add mapping for all the themes you might have
    switch (theme) {
      default:
        return dracula;
    }
  }, [theme]);

  return (
    <ReactCodeMirror
      readOnly={disabled}
      value={code}
      height="200px"
      onChange={onChange}
      extensions={extensions}
      theme={codeMirrorTheme}
    />
  );
}

This uses @uiw/react-codemirror to make the whole thing simple!

royletron avatar Oct 12 '22 07:10 royletron