Lightweight, extensible code editor component for React apps
npm install prism-react-editorreact and react-dom version 16.8.0 or greater installed.
jsx
import { Editor } from "prism-react-editor"
import { BasicSetup } from "prism-react-editor/setups"
// Adding the JSX grammar
import "prism-react-editor/prism/languages/jsx"
// Adds comment toggling and auto-indenting for JSX
import "prism-react-editor/languages/jsx"
import "prism-react-editor/layout.css"
import "prism-react-editor/themes/github-dark.css"
// Required by the basic setup
import "prism-react-editor/search.css"
import "prism-react-editor/invisibles.css"
function MyEditor() {
return
}
`
Props
| Name | Type | Description |
| ------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| language | string | Language used for syntax highlighting. Defaults to text. |
| tabSize | number | Tab size used for indentation. Defaults to 2. |
| insertSpaces | boolean | Whether the editor should insert spaces for indentation. Defaults to true. Requires useDefaultCommands() extension to work. |
| lineNumbers | boolean | Whether line numbers should be shown. Defaults to true. |
| readOnly | boolean | Whether the editor should be read only. Defaults to false. |
| wordWrap | boolean | Whether the editor should have word wrap. Defaults to false. |
| value | string | Initial value to display in the editor. |
| rtl | boolean | Whether the editor uses right to left directionality. Defaults to false. Requires extra CSS from prism-react-editor/rtl-layout.css to work. |
| style | Omit | Allows adding inline styles to the container element. |
| className | string | Additional classes for the container element. |
| textareaProps | Omit | Allows adding props to the editor's textarea element. |
| onUpdate | (value: string, editor: PrismEditor) => void | Function called after the editor updates. |
| onSelectionChange | (selection: InputSelection, value: string, editor: PrismEditor) => void | Function called when the editor's selection changes. |
| onTokenize | (tokens: TokenStream, language: string, value: string, editor: PrismEditor) => void | Function called before the tokens are stringified to HTML. |
| children | React.ReactNode | Extensions and overlays for the editor. |
Pitfall
This component is not controlled, and the value prop should be treated like an initial value. Do not change the value prop in the onUpdate handler. Doing so will negatively impact performance and reset both the cursor position and undo/redo history on every input.
`jsx
// counterexample: do NOT do this
function MyEditor() {
const [value, setValue] = useState("const foo = 'bar'")
return (
)
}
`
If you need access to the editor's value in your component, use a ref instead:
`tsx
function MyEditor() {
const editorRef = useRef()
useEffect(() => {
console.log(editorRef.current?.value)
})
return
}
`
Extensions
To keep the core light, most functionality is added by optional extensions.
There are extensions adding:
- Many common commands
- Bracket matching and rainbow brackets
- Tag matching
- Indentation guides
- Search, regex search and replace
- Selection match highlighting
- A copy button
- Read-only code folding
- Custom undo/redo
- And more...
Many commonly used extensions are added by BasicSetup, but if you want to fully customize which extensions are added. Below it's shown how to import most extensions.
`tsx
import { Editor, PrismEditor } from "prism-react-editor"
import "prism-react-editor/prism/languages/jsx"
import "prism-react-editor/layout.css"
// Needed for the search widget
import "prism-react-editor/search.css"
// Needed for the copy button
import "prism-react-editor/copy-button.css"
import { useBracketMatcher } from "prism-react-editor/match-brackets"
import { useHighlightBracketPairs } from "prism-react-editor/highlight-brackets"
import { IndentGuides } from "prism-react-editor/guides"
import { useHighlightSelectionMatches, useSearchWidget, useShowInvisibles } from "prism-react-editor/search"
import { useHighlightMatchingTags, useTagMatcher } from "prism-react-editor/match-tags"
import { useCursorPosition } from "prism-react-editor/cursor"
import { useDefaultCommands, useEditHistory } from "prism-react-editor/commands"
import { useCopyButton } from "prism-react-editor/copy-button"
import { useOverscroll } from "prism-react-editor/overscroll"
import { usePrismEditor } from "prism-react-editor/extensions"
function MyExtensions() {
const [editor] = usePrismEditor()
useBracketMatcher(editor)
useHighlightBracketPairs(editor)
useOverscroll(editor)
useTagMatcher(editor)
useHighlightMatchingTags(editor)
useDefaultCommands(editor)
useEditHistory(editor)
useSearchWidget(editor)
useHighlightSelectionMatches(editor)
useShowInvisibles(editor)
useCopyButton(editor)
useCursorPosition(editor)
return
}
function MyEditor() {
return (
)
}
`
Lazy loading extensions is also possible for code splitting. It's not recommended to lazy load useBracketMatcher and you might want IndentGuides to be present on first render. All other extensions will work perfectly fine when lazy loaded.
`jsx
import { lazy, Suspense } from "react"
import { usePrismEditor } from "prism-react-editor/extensions"
const LazyExtensions = lazy(() => import("./extensions"))
function MyExtensions() {
const [editor] = usePrismEditor()
useBracketMatcher(editor)
return
}
function MyEditor() {
return (
)
}
`
$3
If you need to do anything more than adding an onUpdate or onSelectionChange prop, you should consider creating your own extension.
`jsx
import { useLayoutEffect, useEffect } from "react"
import { Editor } from "prism-react-editor"
import { BasicSetup } from "prism-react-editor/setups"
import { usePrismEditor } from "prism-react-editor/extensions"
function MyExtension() {
const [editor] = usePrismEditor()
// Layout effects will run before the editor has mounted
useLayoutEffect(() => {
return editor.on("selectionChange", selection => {
console.log("Selection changed:", selection)
})
}, [])
useEffect(() => {
// The editor has mounted now
editor.textarea!.focus()
}, [])
// The elements returned are added to the editor's overlays
// Keep in mind that they will get some default styles
return (
<>
My overlay
>
)
}
function MyEditor() {
return (
)
}
`
Editor API
To access the editor inside an extension, use the usePrismEditor() hook:
`tsx
import { usePrismEditor } from "prism-react-editor/extensions"
function MyExtension() {
const [editor, props] = usePrismEditor()
// ...
}
`
Note: editor is a ref value, so its reference is stable. However, props do become stale, but editor.props can be used to always get the latest props.
$3
- value: string: Current value of the editor.
- activeLine: number: Line number of the line with the cursor. You can index into editor.lines to get the DOM node for the active line.
- inputCommandMap: Record: Record mapping an input to a function called when that input is typed.
- keyCommandMap: Record: Record mapping KeyboardEvent.key to a function called when that key is pressed.
- extensions: Object: Object storing some of the extensions added to the editor. Read more.
- props: EditorProps: The component props passed to the editor.
- focused: boolean. Whether the textarea is focused.
- tokens: TokenStream. Current tokens displayed in the editor.
#### DOM Elements
- container: HTMLDivElement: This is the outermost element of the editor.
- wrapper: HTMLDivElement: Element wrapping the lines and overlays.
- lines: HTMLCollectionOf: Collection containing the overlays as the first element, followed by all code lines.
- textarea: HTMLTextAreaElement: Underlying textarea in the editor.
$3
- update(): void: Forces the editor to update. Can be useful after modifying a grammar for example.
- getSelection(): InputSelection: Gets the selectionStart, selectionEnd and selectionDirection for the textarea.
- on: Adds a listener for editor events and returns a cleanup function. Intended to be used by extensions inside a useLayoutEffect or useEffect hook.
$3
Multiple extensions have an entry on editor.extensions allowing you to interact with the extension.
- matchBrackets: BracketMatcher: Allows access to all brackets found in the editor along with which are paired together.
- matchTags: TagMatcher: Allows access to all tags found in the editor along with which tags are paired together.
- cursor: Cursor: Allows you to get the cursor position relative to the editor's overlays and to scroll the cursor into view.
- searchWidget: SearchWidget: Allows you to open or close the search widget.
- history: EditHistory: Allows you to clear the history or navigate it.
- folding: ReadOnlyCodeFolding: Allows access to the full unfolded code and to toggle folded ranges.
- autoComplete: AutoComplete: Allows inserting snippets and starting completion queries programmatically.
$3
Using things like editor.value or editor.getSelection() to render an extension won't cause the extension to rerender when these values change. Instead, use the helpers that store the value or selection in state and subscribe to updates.
`jsx
import {
usePrismEditor,
useEditorValue,
useEditorSelection
} from "prism-react-editor/extensions"
function MyExtension() {
const [editor, props] = usePrismEditor()
const value = useEditorValue(editor)
const selection = useEditorSelection(editor)
// ...
}
`
Utilities
The prism-react-editor/utils entry point exports various utilities for inserting text, changing the selection, finding token elements, and more.
Prism
The Prism instance used by this library is exported from prism-react-editor/prism. This allows you to add your own Prism grammars or perform syntax highlighting outside of an editor. All modules under prism-react-editor/prism can run outside the browser in for example Node.js to do syntax highlighting on the server. Check the working with prism guide for more info.
Languages
Prism supports syntax highlighting for hundreds of languages, but none of them are imported by default. You need to choose which languages to import. Importing prism-react-editor/prism/languages/javascript for example will register the JavaScript grammar through side effects.
If you need access to many languages, you can import the following entry points:
- prism-react-editor/prism/languages for all languages (~180kB)
- prism-react-editor/prism/languages/common for 42 common languages (~30kB)
This library also supports auto-indenting, comment toggling and self-closing tags for most of these languages. For it to work, you need the useDefaultCommands() hook (or the basic setup) and to import the behavior for the language.
The easiest way is to import all languages at ~3.6kB gzipped. You can dynamically import this since it's usually not needed before the page has loaded.
`javascript
import("prism-react-editor/languages")
`
You can also import prism-react-editor/languages/common instead to support a subset of common languages at less than 2kB gzipped.
Lastly, if you only need support for a few languages, you can do individual imports, for example prism-react-editor/languages/html. Read more.
Styling
This library does not inject any styles onto the webpage, instead you must import them. If the default styles don't work for you, you can import your own styles instead.
- prism-react-editor/layout.css: layout for the editor.
- prism-react-editor/scrollbar.css: custom scrollbar to desktop Chrome and Safari you can color with --pce-scrollbar.
- prism-react-editor/copy-button.css: styles for the useCopybutton() extension.
- prism-react-editor/search.css: styles for the useSearchWidget() extension.
- prism-react-editor/rtl-layout.css: adds support for the rtl prop.
- prism-react-editor/invisibles.css: styles for the useShowInvisibles() extension.
- prism-react-editor/cursor.css: styles for the useCustomCursor() extension.
- prism-react-editor/autocomplete.css: styles for the useAutoComplete() extension.
- prism-react-editor/autocomplete-icons.css: default icons for the autocompletion tooltip.
- prism-react-editor/code-block.css: additional styles required for code blocks.
By default, the editor's height will fit the content, so you might want to add a height or max-height to .prism-code-editor depending on your use case.
Themes
There are currently 14 different themes you can import, one of them being from prism-react-editor/themes/github-dark.css. If none of the themes fit your website, use one of them as an example to help implement your own.
$3
If you're making a theme switcher, you might want to use the useEditorTheme hook. This hook is a simple wrapper around the loadTheme utility exported from the same entry point. If want something more sophisticated, use loadTheme directly instead.
`jsx
import { useState } from "react"
import { useEditorTheme } from "prism-react-editor/themes"
export function App() {
const [theme, setTheme] = useState("github-dark")
const themeCss = useEditorTheme(theme)
return <>
...
>
}
`
The hook and . Alternatively, you can avoid rendering editors before the theme has loaded using themeCss && .
If you're just switching between two themes (light/dark), using CSS variables would have fewer downsides, but this does require maintaining your own theme.
$3
If you want to use your own themes with useEditorTheme or loadTheme or want to override existing themes, use registerTheme. The example below might look different if you're not using Vite as your bundler.
`js
import { registerTheme } from "prism-react-editor/themes"
// Might look different if you're not using Vite
registerTheme("my-theme", () => import("./my-theme.css?inline"))
`
Code blocks
This library can also create static code blocks. These support some features not supported by editors such as hover descriptions and highlighting brackets/tag-names on hover.
`tsx
import {
CodeBlock,
CopyButton,
HighlightBracketPairsOnHover,
HighlightTagPairsOnHover,
HoverDescriptions,
rainbowBrackets,
} from "prism-react-editor/code-blocks"
import "prism-react-editor/layout.css"
import "prism-react-editor/code-block.css"
import "prism-react-editor/themes/github-dark.css"
// Very important for performance to keep this function stable
const onTokenize = rainbowBrackets()
function MyCodeBlock({ lang, code }: { lang: string, code: string }) {
return (
callback={(types, language, text, element) => {
if (types.includes("string")) return ["This is a string token."]
}}
/>
)
}
`
$3
Just like with editors, you can also pass extensions to code blocks that modify them. To access the code block and its props from an extension, use the usePrismCodeBlock() hook:
`jsx
import { usePrismCodeBlock } from "prism-react-editor/code-blocks"
function MyCodeBlockExtension() {
const [codeBlock, props] = usePrismCodeBlock()
// ...
}
`
$3
| Name | Type | Description |
| ------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| language | string | Language used for syntax highlighting. Defaults to text. |
| tabSize | number | Tab size used for indentation. Defaults to 2. |
| lineNumbers | boolean | Whether line numbers should be shown. Defaults to false. |
| wordWrap | boolean | Whether the code block should have word wrap. Defaults to false. |
| preserveIndent | boolean | Whether or not indentation is preserved on wrapped lines. Defaults to true when wordWrap is enabled. |
| guideIndents | boolean | Whether or not to display indentation guides. Does not work with rtl set to true. Defaults to false |
| rtl | boolean | Whether the editor uses right to left directionality. Defaults to false. Requires extra CSS from prism-react-editor/rtl-layout.css to work. |
| code | string | Code to display in the code block. |
| style | Omit | Allows adding inline styles to the container element. |
| className | string | Additional classes for the container element. |
| onTokenize | (tokens: TokenStream) => void | Callback that can be used to modify the tokens before they're stringified to HTML. |
| children | (codeBlock: PrismCodeBlock, props: CodeBlockProps) => React.ReactNode` | Callback used to render extensions. |