Skip to content
This repository was archived by the owner on Apr 6, 2023. It is now read-only.

Latest commit

 

History

History
67 lines (51 loc) · 1.91 KB

File metadata and controls

67 lines (51 loc) · 1.91 KB
title React Simple Code Editor
description Learn how to use React Simple Code Editor with Unform

React Simple Code Editor is a cool library focused on providing a simple way to add a code input source to user.

⚠️ All examples below are using TypeScript. If you're not using it, you can remove all type definitions from the component definition.

Syntax Highlight

React Simple Code Editor use PrismJS to add syntax highlighting to code.

You need to import each language that you want to use from prismjs/components/prism-{language}.

You can also import custom themes from prismjs/themes/prism-{theme}.css.

Example

Below you can see an example using only HTML/CSS syntax highlighting and using prism-dark theme.

import React, { useRef, useState, useEffect } from 'react';
import Editor from 'react-simple-code-editor';
import { useField } from '@unform/core';

import { highlight, languages } from 'prismjs';

import 'prismjs/components/prism-markup';
import 'prismjs/components/prism-css';
import 'prismjs/themes/prism-dark.css';

interface Props {
  name: string;
}

export default function CodeInput({ name }: Props) {
  const [code, setCode] = useState('');
  const editorRef = useRef(null);

  const { defaultValue, fieldName, registerField, error } = useField(name);

  useEffect(() => {
    registerField({
      name: fieldName,
      ref: editorRef.current,
      path: '_input.value',
      setValue(_: any, value: string) {
        setCode(value);
      },
    });
  }, [fieldName, registerField]);

  return (
    <Editor
      className="editor"
      textareaId={fieldName}
      value={code}
      defaultValue={defaultValue}
      onValueChange={setCode}
      highlight={code => highlight(code, languages.markup, 'markup')}
      padding={15}
      ref={editorRef}
    />
  );
};