
Security News
Axios Supply Chain Attack Reaches OpenAI macOS Signing Pipeline, Forces Certificate Rotation
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.
prism-react-editor
Advanced tools
Code editor component for React apps
This is a rewrite of Prism code editor using React and hooks. It's a lightweight, extensible code editor optimized for fast load times with many optional extensions.
npm i prism-react-editor
You must already have react and react-dom version 16.8.0 or greater installed.
Prism code editor's demo. There's no demo for this React rewrite since its behavior is nearly identical.
Below is an example of a simple JSX editor.
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 <Editor language="jsx" value="const foo = 'bar'">
<BasicSetup />
</Editor>
}
| 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<React.CSSProperties, "tabSize"> | Allows adding inline styles to the container element. |
className | string | Additional classes for the container element. |
textareaProps | Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, OmittedTextareaProps> | 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. |
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.
// counterexample: do NOT do this
function MyEditor() {
const [value, setValue] = useState("const foo = 'bar'")
return (
<Editor language="jsx" value={value} onUpdate={setValue} />
)
}
If you need access to the editor's value in your component, use a ref instead:
function MyEditor() {
const editorRef = useRef<PrismEditor>()
useEffect(() => {
console.log(editorRef.current?.value)
})
return <Editor ref={editorRef} />
}
To keep the core light, most functionality is added by optional extensions.
There are extensions adding:
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.
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 <IndentGuides />
}
function MyEditor() {
return (
<Editor language="jsx" value="const foo = 'bar'">
<MyExtensions />
</Editor>
)
}
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.
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 <IndentGuides />
}
function MyEditor() {
return (
<Editor language="jsx" value="const foo = 'bar'">
<MyExtensions />
<Suspense>
<LazyExtensions />
</Suspense>
</Editor>
)
}
If you need to do anything more than adding an onUpdate or onSelectionChange prop, you should consider creating your own extension.
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 (
<>
<div>My overlay</div>
<BasicSetup />
</>
)
}
function MyEditor() {
return (
<Editor language="jsx" value="const foo = 'bar'">
<MyExtension />
</Editor>
)
}
To access the editor inside an extension, use the usePrismEditor() hook:
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.
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<string, InputCommandCallback | null | undefined>: Record mapping an input to a function called when that input is typed.keyCommandMap: Record<string, KeyCommandCallback | null | undefined>: 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.container: HTMLDivElement: This is the outermost element of the editor.wrapper: HTMLDivElement: Element wrapping the lines and overlays.lines: HTMLCollectionOf<HTMLDivElement>: Collection containing the overlays as the first element, followed by all code lines.textarea: HTMLTextAreaElement: Underlying textarea in the editor.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<T extends keyof EditorEventMap>(name: T, listener: EditorEventMap[T]): () => void: Adds a listener for editor events and returns a cleanup function. Intended to be used by extensions inside a useLayoutEffect or useEffect hook.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.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.
import {
usePrismEditor,
useEditorValue,
useEditorSelection
} from "prism-react-editor/extensions"
function MyExtension() {
const [editor, props] = usePrismEditor()
const value = useEditorValue(editor)
const selection = useEditorSelection(editor)
// ...
}
The prism-react-editor/utils entry point exports various utilities for inserting text, changing the selection, finding token elements, and more.
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.
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.
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.
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.
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.
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.
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 <>
<style>{themeCss}</style>
...
</>
}
The hook and <style> tag can be placed in any component you want. Just make sure that component is only used once since you don't want multiple <style> elements with themes on the page.
To limit FOUC, you may want to provide a fallback stylesheet for when the theme is loading using something like <style>{themeCss ?? fallbackCss}</style>. Alternatively, you can avoid rendering editors before the theme has loaded using themeCss && <Editor ... />.
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.
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.
import { registerTheme } from "prism-react-editor/themes"
// Might look different if you're not using Vite
registerTheme("my-theme", () => import("./my-theme.css?inline"))
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.
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 (
<CodeBlock language={lang} code={code} onTokenize={onTokenize}>
<HoverDescriptions
callback={(types, language, text, element) => {
if (types.includes("string")) return ["This is a string token."]
}}
/>
<CopyButton />
<HighlightTagPairsOnHover />
<HighlightBracketPairsOnHover />
</CodeBlock>
)
}
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:
import { usePrismCodeBlock } from "prism-react-editor/code-blocks"
function MyCodeBlockExtension() {
const [codeBlock, props] = usePrismCodeBlock()
// ...
}
| 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<React.CSSProperties, "tabSize" | "counterReset"> | 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. |
Manual DOM manipulation has been kept almost everywhere. This rewrite therefore has very similar performance to the original which would not be the case if only JSX was used.
To run the development server locally, install dependencies.
pnpm install
Next, you must build the prism-code-editor package.
cd ../package
pnpm install
pnpm build
Finally, you can run the development server to test your changes.
cd ../react-package
pnpm dev
FAQs
Lightweight, extensible code editor component for React apps
We found that prism-react-editor demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
OpenAI rotated macOS signing certificates after a malicious Axios package reached its CI pipeline in a broader software supply chain attack.

Security News
Open source is under attack because of how much value it creates. It has been the foundation of every major software innovation for the last three decades. This is not the time to walk away from it.

Security News
Socket CEO Feross Aboukhadijeh breaks down how North Korea hijacked Axios and what it means for the future of software supply chain security.