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 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.
1import React, { useRef, useState, useEffect } from 'react';2import Editor from 'react-simple-code-editor';3import { useField } from '@unform/core';45import { highlight, languages } from 'prismjs';67import 'prismjs/components/prism-markup';8import 'prismjs/components/prism-css';9import 'prismjs/themes/prism-dark.css';1011interface Props {12 name: string;13}1415export default function CodeInput({ name }: Props) {16 const [code, setCode] = useState('');17 const editorRef = useRef(null);1819 const { defaultValue, fieldName, registerField, error } = useField(name);2021 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]);3132 return (33 <Editor34 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};