| 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.
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.
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}
/>
);
};