tRuEsAtM
tRuEsAtM

Reputation: 3678

How to use Monaco Editor in a React functional component?

I have a functional component in my React project. I have included the Monaco editor dependency as

import * as Monaco from 'monaco-editor/esm/vs/editor/editor.api';

How to use Editor object from here to actually render and test things for monaco-editor?

I have code like below,

  return (
    <Flex>
      <Flex.Box auto>
        <Input.Textarea
          ref={ref}
          size="small"
          value={value}
          onChange={onChange}
          onKeyPress={(e) => { handleKeyDown(e, value); }}
          error={error}
          readOnly={readOnly}
        />
        <MonacoEnvironment.
      </Flex.Box>
      <Flex align="flex-start" w="21px">
        {icon}
      </Flex>
    </Flex>
  );

I am looking at MonacoEnvironment object, but I am clueless about setting it up as an Editor.

I want to mimick the below functionality in my code,

monaco.editor.create(document.getElementById('container'), {
  value: [
    'function x() {',
    '\tconsole.log("Hello world!");',
    '}'
  ].join('\n'),
  language: 'javascript'
});

Upvotes: 0

Views: 2526

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53512

I see two options for you here:

  1. Add an HTML element to your render tree, which can host the editor. You have the document.getElementById call in the second code snippet. This requires an element with the id container:
  return (
    <Flex>
      <Flex.Box auto>
        <Input.Textarea
          ref={ref}
          size="small"
          value={value}
          onChange={onChange}
          onKeyPress={(e) => { handleKeyDown(e, value); }}
          error={error}
          readOnly={readOnly}
        />
        <div id="container />
      </Flex.Box>
      <Flex align="flex-start" w="21px">
        {icon}
      </Flex>
    </Flex>
  );
  1. Use a Monaco editor React wrapper (e.g. react-monaco-editor) and add it to your render tree:
  return (
    <Flex>
      <Flex.Box auto>
        <Input.Textarea
          ref={ref}
          size="small"
          value={value}
          onChange={onChange}
          onKeyPress={(e) => { handleKeyDown(e, value); }}
          error={error}
          readOnly={readOnly}
        />
        <MonacoEditor
          width="800"
          height="600"
          language="javascript"
          theme="vs-dark"
          value={code}
          options={options}
        />
      </Flex.Box>
      <Flex align="flex-start" w="21px">
        {icon}
      </Flex>
    </Flex>
  );

You don't need that second part then, where you manually created the editor.

Upvotes: 0

Related Questions