Unform

React Simple Code Editor

React Simple Code Editor

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 simply remove all type definitions as the React.FC<Props> from 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.

1import React, { useRef, useState, useEffect } from 'react';
2import Editor from 'react-simple-code-editor';
3import { useField } from '@unform/core';
4
5import { highlight, languages } from 'prismjs';
6
7import 'prismjs/components/prism-markup';
8import 'prismjs/components/prism-css';
9import 'prismjs/themes/prism-dark.css';
10
11interface Props {
12 name: string;
13}
14
15const CodeInput: React.FC<Props> = ({ name }) => {
16 const [code, setCode] = useState('');
17 const editorRef = useRef(null);
18
19 const { defaultValue, fieldName, registerField, error } = useField(name);
20
21 useEffect(() => {
22 registerField({
23 name: fieldName,
24 ref: editorRef.current,
25 path: '_input.value',
26 setValue(_: any, value: string) {
27 setCode(value);
28 },
29 });
30 }, [fieldName, registerField]);
31
32 return (
33 <Editor
34 className="editor"
35 textareaId={fieldName}
36 value={code}
37 defaultValue={defaultValue}
38 onValueChange={setCode}
39 highlight={code => highlight(code, languages.markup, 'markup')}
40 padding={15}
41 ref={editorRef}
42 />
43 );
44};
45
46export default CodeInput;
Edit this page on GitHub