{"id":15025728,"url":"https://github.com/formidablelabs/prism-react-renderer","last_synced_at":"2025-05-11T05:45:14.521Z","repository":{"id":40244648,"uuid":"145147121","full_name":"FormidableLabs/prism-react-renderer","owner":"FormidableLabs","description":"🖌️ Renders highlighted Prism output to React (+ theming \u0026 vendored Prism)","archived":false,"fork":false,"pushed_at":"2025-01-02T18:23:10.000Z","size":2370,"stargazers_count":1940,"open_issues_count":9,"forks_count":151,"subscribers_count":35,"default_branch":"master","last_synced_at":"2025-05-11T05:44:58.232Z","etag":null,"topics":["highlight","prismjs","react","reactjs"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FormidableLabs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-08-17T17:11:38.000Z","updated_at":"2025-05-10T06:39:47.000Z","dependencies_parsed_at":"2023-02-01T14:00:32.589Z","dependency_job_id":"5b3fce77-3a18-4016-905c-f70ca24694bd","html_url":"https://github.com/FormidableLabs/prism-react-renderer","commit_stats":{"total_commits":199,"total_committers":45,"mean_commits":"4.4222222222222225","dds":0.6834170854271358,"last_synced_commit":"e35950e4f9520f33672e94b798eadfd426ef692d"},"previous_names":[],"tags_count":37,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FormidableLabs%2Fprism-react-renderer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FormidableLabs%2Fprism-react-renderer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FormidableLabs%2Fprism-react-renderer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FormidableLabs%2Fprism-react-renderer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FormidableLabs","download_url":"https://codeload.github.com/FormidableLabs/prism-react-renderer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253523717,"owners_count":21921818,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["highlight","prismjs","react","reactjs"],"created_at":"2024-09-24T20:02:55.031Z","updated_at":"2025-05-11T05:45:14.450Z","avatar_url":"https://github.com/FormidableLabs.png","language":"TypeScript","readme":"\u003ca href=\"https://commerce.nearform.com/open-source/\" target=\"_blank\"\u003e\r\n  \u003cimg alt=\"Prism React Renderer\" src=\"https://oss.nearform.com/api/banner.svg?text=prism+react+renderer\" /\u003e\r\n\u003c/a\u003e\r\n\r\n\u003cp align=\"center\" style=\"font-size: 1.2rem;\"\u003e\r\n  A lean \u003ca href=\"https://github.com/PrismJS/prism\"\u003ePrism\u003c/a\u003e highlighter component for React\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  \u003ca href=\"https://npmjs.com/package/prism-react-renderer\"\u003e\u003cimg src=\"https://img.shields.io/npm/dm/prism-react-renderer.svg\"\u003e\u003c/a\u003e\r\n  \u003ca href=\"https://npmjs.com/package/prism-react-renderer\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/prism-react-renderer.svg\"\u003e\u003c/a\u003e\r\n  \u003ca href=\"https://github.com/FormidableLabs/prism-react-renderer#maintenance-status\"\u003e\r\n    \u003cimg alt=\"Maintenance Status\" src=\"https://img.shields.io/badge/maintenance-active-green.svg\" /\u003e\r\n  \u003c/a\u003e\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  Comes with everything to render Prismjs syntax highlighted code directly in React \u0026 React Native!\r\n\u003c/p\u003e\r\n\r\n## Introduction\r\n\r\nPrism React Renderer powers syntax highlighting in the amazing [Docusaurus](https://docusaurus.io/) framework and many others.\r\n\r\nThis library tokenises code using Prism and provides a small render-props-driven\r\ncomponent to quickly render it out into React. This is why it even works with\r\nReact Native! It's bundled with a modified version of Prism that won't pollute\r\nthe global namespace and comes with\r\n[a couple of common language syntaxes](./packages/generate-prism-languages/index.ts#L9-L23).\r\n\r\n_(There's also an [escape-hatch](https://github.com/FormidableLabs/prism-react-renderer#prism) to use your own Prism setup, just in case)_\r\n\r\nIt also comes with its own [VSCode-like theming format](#theming), which means by default\r\nyou can easily drop in different themes, use the ones this library ships with, or\r\ncreate new ones programmatically on the fly.\r\n\r\n_(If you just want to use your Prism CSS-file themes, that's also no problem)_\r\n\r\n## Table of Contents\r\n\r\n\u003c!-- START doctoc generated TOC please keep comment here to allow auto update --\u003e\r\n\r\n- [Installation](#installation)\r\n  - [Usage](#usage)\r\n  - [Custom Language Support](#custom-language-support)\r\n- [Basic Props](#basic-props)\r\n  - [children](#children)\r\n  - [language](#language)\r\n  - [code](#code)\r\n- [Advanced Props](#advanced-props)\r\n  - [theme](#theme)\r\n  - [prism](#prism)\r\n- [Children Function](#children-function)\r\n  - [state](#state)\r\n  - [prop getters](#prop-getters)\r\n    - [`getLineProps`](#getlineprops)\r\n    - [`getTokenProps`](#gettokenprops)\r\n- [Utility Functions](#utility-functions)\r\n  - [`useTokenize`](#usetokenize)\r\n  - [`normalizeTokens`](#normalizetokens)\r\n- [Theming](#theming)\r\n  - [Using a built-in theme](#using-a-built-in-theme)\r\n  - [Providing a CSS based theme](#providing-a-css-based-theme)\r\n- [Upgrade](#upgrade)\r\n  - [Change module imports](#change-module-imports)\r\n  - [Change theme imports](#change-theme-imports)\r\n  - [Check language support](#check-language-support)\r\n  - [Add language component](#add-language-component)\r\n- [Development](#development)\r\n  - [Local Demo](#local-demo)\r\n- [LICENSE](#license)\r\n- [Maintenance Status](#maintenance-status)\r\n\r\n\u003c!-- END doctoc generated TOC please keep comment here to allow auto update --\u003e\r\n\r\n## Installation\r\n\r\nThis module is distributed via npm which is bundled with node and\r\nshould be installed as one of your project's `dependencies`:\r\n\r\n```sh\r\n# npm\r\nnpm install --save prism-react-renderer\r\n# yarn\r\nyarn add prism-react-renderer\r\n# pnpm\r\npnpm add prism-react-renderer\r\n```\r\n\r\n\u003e Prism React Renderer has a peer dependency on `react`\r\n\r\n### Usage\r\n\r\nPrism React Renderer has a named export for the `\u003cHighlight /\u003e` component along with `themes`. To see Prism React Render in action with base styling, clone the repo and follow the [steps for local development](#development).\r\n\r\n```tsx\r\nimport React from \"react\"\r\nimport ReactDOM from \"react-dom/client\"\r\nimport { Highlight, themes } from \"prism-react-renderer\"\r\nimport styles from 'styles.module.css'\r\n\r\nconst codeBlock = `\r\nconst GroceryItem: React.FC\u003cGroceryItemProps\u003e = ({ item }) =\u003e {\r\n  return (\r\n    \u003cdiv\u003e\r\n      \u003ch2\u003e{item.name}\u003c/h2\u003e\r\n      \u003cp\u003ePrice: {item.price}\u003c/p\u003e\r\n      \u003cp\u003eQuantity: {item.quantity}\u003c/p\u003e\r\n    \u003c/div\u003e\r\n  );\r\n}\r\n`\r\n\r\nexport const App = () =\u003e (\r\n  \u003cHighlight\r\n    theme={themes.shadesOfPurple}\r\n    code={codeBlock}\r\n    language=\"tsx\"\r\n  \u003e\r\n    {({ className, style, tokens, getLineProps, getTokenProps }) =\u003e (\r\n      \u003cpre style={style}\u003e\r\n        {tokens.map((line, i) =\u003e (\r\n          \u003cdiv key={i} {...getLineProps({ line })}\u003e\r\n            \u003cspan\u003e{i + 1}\u003c/span\u003e\r\n            {line.map((token, key) =\u003e (\r\n              \u003cspan key={key} {...getTokenProps({ token })} /\u003e\r\n            ))}\r\n          \u003c/div\u003e\r\n        ))}\r\n      \u003c/pre\u003e\r\n    )}\r\n  \u003c/Highlight\u003e\r\n)\r\n\r\nReactDOM\r\n  .createRoot(document.getElementById(\"root\") as HTMLElement)\r\n  .render(\u003cApp /\u003e)\r\n```\r\n\r\n### Custom Language Support\r\n\r\nBy default `prism-react-renderer` only includes a [base set of languages](https://github.com/FormidableLabs/prism-react-renderer/blob/master/packages/generate-prism-languages/index.ts#L9-L23) that Prism supports. \r\n\r\n\u003e _Note_: Some languages (such as Javascript) are part of the bundle of other languages\r\n\r\n**Depending on your app's build system you may need to `await` the `import` or use `require` to ensure `window.Prism` exists before importing the custom languages.** You can add support for more by including their definitions from the main `prismjs` package:\r\n\r\n```js\r\nimport { Highlight, Prism } from \"prism-react-renderer\";\r\n\r\n(typeof global !== \"undefined\" ? global : window).Prism = Prism\r\nawait import(\"prismjs/components/prism-applescript\")\r\n/** or **/\r\nrequire(\"prismjs/components/prism-applescript\")\r\n```\r\n\r\n\r\n## Basic Props\r\n\r\nThis is the list of props that you should probably know about. There are some\r\n[advanced props](#advanced-props) below as well.\r\n\r\nMost of these [advanced props](#advanced-props) are included in the `defaultProps`.\r\n\r\n### children\r\n\r\n\u003e `function({})` | _required_\r\n\r\nThis is called with an object. Read more about the properties of this object in\r\nthe section \"[Children Function](#children-function)\".\r\n\r\n### language\r\n\r\n\u003e `string` | _required_\r\n\r\nThis is the language that your code will be highlighted as. You can see a list\r\nof all languages that are supported out of the box [here](./packages/generate-prism-languages/index.ts#L9-L23). Not all languages are included and the list of languages that are currently is a little arbitrary. You can use the [escape-hatch](https://github.com/FormidableLabs/prism-react-renderer#prism) to use your own Prism setup, just in case, or [add more languages to the bundled Prism.](https://github.com/FormidableLabs/prism-react-renderer#faq)\r\n\r\n### code\r\n\r\n\u003e `string` | _required_\r\n\r\nThis is the code that will be highlighted.\r\n\r\n## Advanced Props\r\n\r\n### theme\r\n\r\n\u003e `PrismTheme` | _optional; default is vsDark_\r\n\r\nIf a theme is passed, it is used to generate style props which can be retrieved\r\nvia the prop-getters which are described in \"[Children Function](#children-function)\".\r\n\r\nRead more about how to theme `prism-react-renderer` in\r\nthe section \"[Theming](#theming)\".\r\n\r\n### prism\r\n\r\n\u003e `prism` | _optional; default is the vendored version_\r\n\r\nThis is the [Prismjs](https://github.com/PrismJS/prism) library itself.\r\nA vendored version of Prism is provided (and also exported) as part of this library.\r\nThis vendored version doesn't pollute the global namespace, is slimmed down,\r\nand doesn't conflict with any installation of `prismjs` you might have.\r\n\r\nIf you're only using `Prism.highlight` you can choose to use `prism-react-renderer`'s\r\nexported, vendored version of Prism instead.\r\n\r\nBut if you choose to use your own Prism setup, simply pass Prism as a prop:\r\n\r\n```jsx\r\n// Whichever way you're retrieving Prism here:\r\nimport Prism from 'prismjs/components/prism-core';\r\n\r\n\u003cHighlight prism={Prism} {/* ... */} /\u003e\r\n```\r\n\r\n## Children Function\r\n\r\nThis is where you render whatever you want to based on the output of `\u003cHighlight /\u003e`.\r\nYou use it like so:\r\n\r\n```js\r\nconst ui = (\r\n  \u003cHighlight\u003e\r\n    {highlight =\u003e (\r\n      // use utilities and prop getters here, like highlight.className, highlight.getTokenProps, etc.\r\n      \u003cpre\u003e{/* more jsx here */}\u003c/pre\u003e\r\n    )}\r\n  \u003c/Highlight\u003e\r\n);\r\n```\r\n\r\nThe properties of this `highlight` object can be split into two categories as indicated below:\r\n\r\n### state\r\n\r\nThese properties are the flat output of `\u003cHighlight /\u003e`. They're generally \"state\" and are what\r\nyou'd usually expect from a render-props-based API.\r\n\r\n| property    | type        | description                                                                                                                  |\r\n| ----------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------- |\r\n| `tokens`    | `Token[][]` | This is a doubly nested array of tokens. The outer array is for separate lines, the inner for tokens, so the actual content. |\r\n| `className` | `string`    | This is the class you should apply to your wrapping element, typically a `\u003cpre\u003e`                                             |\r\n\r\nA \"Token\" is an object that represents a piece of content for Prism. It has a `types` property, which is an array\r\nof types that indicate the purpose and styling of a piece of text, and a `content` property, which is the actual\r\ntext.\r\n\r\nYou'd typically iterate over `tokens`, rendering each line, and iterate over its items, rendering out each token, which is a piece of\r\nthis line.\r\n\r\n### prop getters\r\n\r\n\u003e See\r\n\u003e [Kent C. Dodds' blog post about prop getters](https://blog.kentcdodds.com/how-to-give-rendering-control-to-users-with-prop-getters-549eaef76acf)\r\n\r\nThese functions are used to apply props to the elements that you render. This\r\ngives you maximum flexibility to render what, when, and wherever you like.\r\n\r\nYou'd typically call these functions with some dictated input and add on all other\r\nprops that it should pass through. It'll correctly override and modify the props\r\nthat it returns to you, so passing props to it instead of adding them directly is\r\nadvisable.\r\n\r\n| property        | type           | description                                                                                           |\r\n| --------------- | -------------- | ----------------------------------------------------------------------------------------------------- |\r\n| `getLineProps`  | `function({})` | returns the props you should apply to any list of tokens, i.e. the element that contains your tokens. |\r\n| `getTokenProps` | `function({})` | returns the props you should apply to the elements displaying tokens that you render.                 |\r\n\r\n#### `getLineProps`\r\n\r\nYou need to add a `line` property (type: `Token[]`) to the object you're passing to\r\n`getLineProps`.\r\n\r\nThis getter will return you props to spread onto your line elements (typically `\u003cdiv\u003es`).\r\n\r\nIt will typically return a `className` (if you pass one it'll be appended), `children`,\r\n`style` (if you pass one it'll be merged). It also passes on all other props you pass\r\nto the input.\r\n\r\nThe `className` will always contain `.token-line`.\r\n\r\n#### `getTokenProps`\r\n\r\nYou need to add a `token` property (type: `Token`) to the object you're passing to\r\n`getTokenProps`.\r\n\r\nThis getter will return you props to spread onto your token elements (typically `\u003cspan\u003es`).\r\n\r\nIt will typically return a `className` (if you pass one it'll be appended), `children`,\r\n`style` (if you pass one it'll be merged). It also passes on all other props you pass\r\nto the input.\r\n\r\nThe `className` will always contain `.token`. This also provides full compatibility with\r\nyour old Prism CSS-file themes.\r\n\r\n## Utility Functions\r\n\r\n### `useTokenize`\r\n\r\n\u003e `(options: TokenizeOptions) =\u003e Token[][]`\r\n\r\n```ts\r\ntype TokenizeOptions = {\r\n  prism: PrismLib\r\n  code: string\r\n  grammar?: PrismGrammar\r\n  language: Language\r\n}\r\n\r\n```\r\n\r\nThis is a React hook that tokenizes code using Prism. It returns an array of tokens that can be rendered using the built-in `\u003cHighlight /\u003e` component or your own custom component. It uses `normalizeTokens` internally to convert the tokens into a shape that can be rendered.\r\n\r\n- `prism: PrismLib`: the Prism library to use for tokenization. This can be the vendored version of Prism that is included with `prism-react-renderer` or a custom version of Prism that you have configured.\r\n\r\n- `code: string`: a string containing the code to tokenize.\r\n- `grammar?: PrismGrammar`: a Prism grammar object to use for tokenization. If this is omitted, the tokens will just be normalized. A grammar can be obtained from `Prism.languages` or by importing a language from `prismjs/components/`.\r\n- `language: Language`: the language to use for tokenization. This should be a language that Prism supports.\r\n\r\n### `normalizeTokens`\r\n\r\n\u003e `(tokens: (PrismToken | string)[]) =\u003e Token[][]`\r\n\r\nTakes an array of Prism’s tokens and groups them by line, converting strings into tokens. Tokens can become recursive in some cases which means that their types are concatenated. Plain-string tokens however are always of type `plain`.\r\n\r\n- `PrismToken` is an internal alias for `Token` exported by `prismjs` and is defined [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/prismjs/index.d.ts#L347).\r\n\r\n- `Token` is an internal object that represents a slice of tokenized content for Prism with three properties:\r\n  - `types: string[]`: an array of types that indicate the purpose and styling of a piece of text\r\n  - `content: string`: the content of the token\r\n  - `empty: boolean`: a flag indicating whether the token is empty or not.\r\n\r\n## Theming\r\n\r\n### Using a built-in theme\r\n\r\nThe `defaultProps` you'd typically apply in a basic use-case, contain a default theme.\r\nThis theme is [vsDark](./packages/prism-react-renderer/src/themes/vsDark.ts).\r\n\r\n```jsx\r\nimport { Highlight, themes } from 'prism-react-renderer';\r\n\r\n\u003cHighlight theme={themes.dracula} {/* ... */} /\u003e\r\n```\r\n\r\nThese themes are JSON-based and are heavily inspired by VSCode's theme format.\r\n\r\n```ts\r\nexport type PrismTheme = {\r\n  plain: PrismThemeEntry\r\n  styles: Array\u003c{\r\n    types: string[]\r\n    style: PrismThemeEntry\r\n    languages?: Language[]\r\n  }\u003e\r\n}\r\n```\r\n\r\nThe `plain` property provides a base style-object. This style object is directly used\r\nin the `style` props that you'll receive from the prop getters, if a `theme` prop has\r\nbeen passed to `\u003cHighlight /\u003e`.\r\n\r\nThe `styles` property contains an array of definitions. Each definition contains a `style`\r\nproperty, that is also just a style object. These styles are limited by the `types`\r\nand `languages` properties.\r\n\r\nThe `types` properties is an array of token types that Prism outputs. The `languages`\r\nproperty limits styles to highlighted languages.\r\n\r\nWhen converting a Prism CSS theme it's mostly just necessary to use classes as\r\n`types` and convert the declarations to object-style-syntax and put them on `style`.\r\n\r\n### Providing a CSS based theme\r\n\r\nIn order to use a CSS based theme like the ones from [PrismJS](https://github.com/PrismJS/prism-themes), you need to disable the built in theme.\r\n\r\n```ts\r\nconst emptyTheme = { plain: {}, styles: [] };\r\n\r\n\u003cHighlight theme={emptyTheme} {/* ... */} /\u003e\r\n```\r\n\r\n## Upgrade\r\n\r\nIf you are migrating from v1.x to v2.x, follow these steps\r\n\r\n### Change module imports\r\n\r\n```diff\r\n- import Highlight, { defaultProps } from \"prism-react-renderer\";\r\n+ import { Highlight } from \"prism-react-renderer\"\r\n\r\nconst Content = (\r\n-  \u003cHighlight {...defaultProps} code={exampleCode} language=\"jsx\"\u003e\r\n+  \u003cHighlight code={exampleCode} language=\"jsx\"\u003e\r\n```\r\n\r\n### Change theme imports\r\n\r\n```diff\r\n- const theme = require('prism-react-renderer/themes/github')\r\n+ const theme = require('prism-react-renderer').themes.github\r\n```\r\n\r\n### Check language support\r\n\r\n\u003e By default prism-react-renderer only includes a base set of languages that Prism supports. Depending on your app's build system you may need to await the import or use require to ensure window.Prism exists before importing the custom languages.\r\n\r\nSee: https://github.com/FormidableLabs/prism-react-renderer#custom-language-support\r\n\r\nInstall prismjs (if not available yet):\r\n\r\n```\r\n# npm\r\nnpm install --save prismjs\r\n# yarn\r\nyarn add prismjs\r\n# pnpm\r\npnpm add prismjs\r\n```\r\n\r\n### Add language component\r\n\r\nIf the language is not already bundled in the above, you can add additional languages with the following code:\r\n\r\n```\r\nimport { Highlight, Prism } from \"prism-react-renderer\";\r\n\r\n(typeof global !== \"undefined\" ? global : window).Prism = Prism\r\nawait import(\"prismjs/components/prism-applescript\")\r\n/** or **/\r\nrequire(\"prismjs/components/prism-applescript\")\r\n```\r\n\r\n## Development\r\n\r\nLocal development setup can be run with the following commands running Node 18.x. This project uses corepack to specify its package manager version and you should have it enabled locally using `corepack enable`.\r\n\r\n```\r\n$ pnpm install\r\n$ pnpm build\r\n$ pnpm test\r\n```\r\n\r\n### Local Demo\r\n\r\nTo run the local demo, ensure you have first run `pnpm build`, then run `pnpm start:demo` and open the provided URL to the demo site in your terminal.\r\n\r\n```\r\n$ pnpm build\r\n$ pnpm start:demo\r\n```\r\n\r\nThe workspace projects are linked, so changes can be hot reloaded during development by running multiple terminals\r\n\r\n```\r\n// terminal 1\r\n$ pnpm build:watch\r\n```\r\n\r\n```\r\n// terminal 2\r\n$ pnpm start:demo\r\n```\r\n\r\n## LICENSE\r\n\r\nMIT\r\n\r\n## Maintenance Status\r\n\r\n**Active:** Nearform is actively working on this project, and we expect to continue work for the foreseeable future. Bug reports, feature requests and pull requests are welcome.\r\n\r\n[maintenance-image]: https://img.shields.io/badge/maintenance-active-green.svg\r\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fformidablelabs%2Fprism-react-renderer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fformidablelabs%2Fprism-react-renderer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fformidablelabs%2Fprism-react-renderer/lists"}