prism-react-renderer

Renders highlighted Prism output to React (+ theming & vendored Prism)

README

[![Maintenance Status][maintenance-image]](#maintenance-status)

  prism-react-renderer 🖌️

A lean Prism highlighter component for React

  Comes with everything to render Prismjs highlighted code directly to React (Native) elements, global-pollution-free!

Why?

Maybe you need to render some extra UI with your Prismjs-highlighted code,
or maybe you'd like to manipulate what Prism renders completely,
or maybe you're just using Prism with React and are searching for an easier,
global-pollution-free way?
Then you're right where you want to be!

How?

This library tokenises code using Prism and provides a small render-props-driven
component to quickly render it out into React. This is why it even works with
React Native! It's bundled with a modified version of Prism that won't pollute
the global namespace and comes with
_(There's also an escape-hatch to use your own Prism setup, just in case)_
It also comes with its own VSCode-like theming format, which means by default
you can easily drop in different themes, use the ones this library ships with, or
create new ones programmatically on the fly.
_(If you just want to use your Prism CSS-file themes, that's also no problem)_

Table of Contents

  - children
  - language
  - code
  - theme
  - Prism
  - state
    - [getLineProps](#getlineprops)
    - [getTokenProps](#gettokenprops)
- FAQ

Installation

This module is distributed via npm which is bundled with node and
should be installed as one of your project's dependencies:
  1. ```sh
  2. # npm
  3. npm install --save prism-react-renderer
  4. # yarn
  5. yarn add prism-react-renderer
  6. ```

This package also depends on react. Please make sure you

have those installed as well.

Usage

Screenshot showing highlighted code block
  1. ``` js
  2. import React from "react";
  3. import { render } from "react-dom";
  4. // import { createRoot } from "react-dom/client";
  5. import Highlight, { defaultProps } from "prism-react-renderer";
  6. const exampleCode = `
  7. (function someDemo() {
  8.   var test = "Hello World!";
  9.   console.log(test);
  10. })();
  11. return () => <App />;
  12. `;
  13. const Content = (
  14.   <Highlight {...defaultProps} code={exampleCode} language="jsx">
  15.     {({ className, style, tokens, getLineProps, getTokenProps }) => (
  16.       <pre className={className} style={style}>
  17.         {tokens.map((line, i) => (
  18.           <div {...getLineProps({ line, key: i })}>
  19.             {line.map((token, key) => (
  20.               <span {...getTokenProps({ token, key })} />
  21.             ))}
  22.           </div>
  23.         ))}
  24.       </pre>
  25.     )}
  26.   </Highlight>
  27. );
  28. render(Content, document.getElementById('root'));
  29. // If you are using React 18
  30. // const root = createRoot(document.getElementById('root'));
  31. // root.render(Content);
  32. ```
`` is the only component exposed by this package, as inspired by
It also exports a defaultProps object which for basic usage can simply be spread
onto the `` component. It also provides some default theming.
It doesn't render anything itself, it just calls the render function and renders that.
`{highlight =>
/* your JSX here! */
}
`

Line Numbers

Add line numbers to your highlighted code blocks using the index parameter in your line.map function:
Screenshot showing line numbers in highlighted code block
For example, if you were using styled-components, it could look like the following demo.

[Demo with styled-components](https://codesandbox.io/s/prism-react-renderer-example-u6vhk?file=/src/WithLineNumbers.js)

  1. ``` js
  2. import React from "react";
  3. import styled from "styled-components";
  4. import Highlight, { defaultProps } from "prism-react-renderer";
  5. import theme from "prism-react-renderer/themes/nightOwl";
  6. const exampleCode = `
  7. import React, { useState } from "react";
  8. function Example() {
  9.   const [count, setCount] = useState(0);
  10.   return (
  11.     <div>
  12.       <p>You clicked {count} times</p>
  13.       <button onClick={() => setCount(count + 1)}>
  14.         Click me
  15.       </button>
  16.     </div>
  17.   );
  18. }
  19. `.trim();
  20. const Pre = styled.pre`
  21.   text-align: left;
  22.   margin: 1em 0;
  23.   padding: 0.5em;
  24.   overflow: scroll;
  25. `;
  26. const Line = styled.div`
  27.   display: table-row;
  28. `;
  29. const LineNo = styled.span`
  30.   display: table-cell;
  31.   text-align: right;
  32.   padding-right: 1em;
  33.   user-select: none;
  34.   opacity: 0.5;
  35. `;
  36. const LineContent = styled.span`
  37.   display: table-cell;
  38. `;
  39. const WithLineNumbers = () => (
  40.   <Highlight {...defaultProps} theme={theme} code={exampleCode} language="jsx">
  41.     {({ className, style, tokens, getLineProps, getTokenProps }) => (
  42.       <Pre className={className} style={style}>
  43.         {tokens.map((line, i) => (
  44.           <Line key={i} {...getLineProps({ line, key: i })}>
  45.             <LineNo>{i + 1}</LineNo>
  46.             <LineContent>
  47.               {line.map((token, key) => (
  48.                 <span key={key} {...getTokenProps({ token, key })} />
  49.               ))}
  50.             </LineContent>
  51.           </Line>
  52.         ))}
  53.       </Pre>
  54.     )}
  55.   </Highlight>
  56. );
  57. export default WithLineNumbers;
  58. ```

Basic Props

This is the list of props that you should probably know about. There are some
advanced props below as well.
Most of these advanced props are included in thedefaultProps.

children

function({}) | _required_

This is called with an object. Read more about the properties of this object in
the section "Children Function".

language

string | _required_

This is the language that your code will be highlighted as. You can see a list
of all languages that are supported out of the box here. Not all languages are included and the list of languages that are currently is a little arbitrary. You can use the escape-hatch to use your own Prism setup, just in case, or add more languages to the bundled Prism.

code

string | _required_

This is the code that will be highlighted.

Advanced Props

theme

PrismTheme | _required; default is provided in defaultProps export_

If a theme is passed, it is used to generate style props which can be retrieved
via the prop-getters which are described in "Children Function".
A default theme is provided by the defaultProps object.
Read more about how to theme prism-react-renderer in
the section "Theming".

Prism

PrismLib | _required; default is provided in defaultProps export_

This is the Prismjs library itself.
A vendored version of Prism is provided (and also exported) as part of this library.
This vendored version doesn't pollute the global namespace, is slimmed down,
and doesn't conflict with any installation of prismjs you might have.
If you're only using Prism.highlight you can choose to use prism-react-renderer's
exported, vendored version of Prism instead.
But if you choose to use your own Prism setup, simply pass Prism as a prop:
  1. ``` js
  2. // Whichever way you're retrieving Prism here:
  3. import Prism from 'prismjs/components/prism-core';
  4. <Highlight Prism={Prism} {/* ... */} />
  5. ```

Children Function

This is where you render whatever you want to based on the output of ``.
You use it like so:
  1. ``` js
  2. const ui = (
  3.   <Highlight>
  4.     {highlight => (
  5.       // use utilities and prop getters here, like highlight.className, highlight.getTokenProps, etc.
  6.       <pre>{/* more jsx here */}</pre>
  7.     )}
  8.   </Highlight>
  9. );
  10. ```
The properties of this highlight object can be split into two categories as indicated below:

state

These properties are the flat output of ``. They're generally "state" and are what
you'd usually expect from a render-props-based API.
propertytypedescription
--------------------------------------------------------------------------------------------------------------------------------------------------
`tokens``Token[][]`This
`className``string`This
A "Token" is an object that represents a piece of content for Prism. It has a types property, which is an array
of types that indicate the purpose and styling of a piece of text, and a content property, which is the actual
text.
You'd typically iterate over tokens, rendering each line, and iterate over its items, rendering out each token, which is a piece of
this line.

prop getters

See

These functions are used to apply props to the elements that you render. This
gives you maximum flexibility to render what, when, and wherever you like.
You'd typically call these functions with some dictated input and add on all other
props that it should pass through. It'll correctly override and modify the props
that it returns to you, so passing props to it instead of adding them directly is
advisable.
propertytypedescription
----------------------------------------------------------------------------------------------------------------------------------
`getLineProps``function({})`returns
`getTokenProps``function({})`returns

getLineProps

You need to add a line property (type: Token[]) to the object you're passing to
getLineProps; It's also advisable to add a key.
This getter will return you props to spread onto your line elements (typically `
s`).
It will typically return a className (if you pass one it'll be appended), children,
style (if you pass one it'll be merged). It also passes on all other props you pass
to the input.
The className will always contain .token-line.

getTokenProps

You need to add a token property (type: Token) to the object you're passing to
getTokenProps; It's also advisable to add a key.
This getter will return you props to spread onto your token elements (typically `s`).
It will typically return a className (if you pass one it'll be appended), children,
style (if you pass one it'll be merged). It also passes on all other props you pass
to the input.
The className will always contain .token. This also provides full compatibility with
your old Prism CSS-file themes.

Theming

The defaultProps you'd typically apply in a basic use-case, contain a default theme.
This theme is duotoneDark.
While all `className`s are provided with ``, so that you could use your good
old Prism CSS-file themes, you can also choose to use prism-react-renderer's themes like so:
  1. ``` js
  2. import dracula from 'prism-react-renderer/themes/dracula';
  3. <Highlight theme={dracula} {/* ... */} />
  4. ```
These themes are JSON-based and are heavily inspired by VSCode's theme format.
Their syntax, expressed in Flow looks like the following:
  1. ``` js
  2. {
  3.   plain: StyleObj,
  4.   styles: Array<{
  5.     types: string[],
  6.     languages?: string[],
  7.     style: StyleObj
  8.   }>
  9. }
  10. ```
The plain property provides a base style-object. This style object is directly used
in the style props that you'll receive from the prop getters, if a theme prop has
been passed to ``.
The styles property contains an array of definitions. Each definition contains a style
property, that is also just a style object. These styles are limited by the types
and languages properties.
The types properties is an array of token types that Prism outputs. The languages
property limits styles to highlighted languages.
When converting a Prism CSS theme it's mostly just necessary to use classes as
types and convert the declarations to object-style-syntax and put them on style.

FAQ

How do I add more language highlighting support?
By default prism-react-renderer only includes an arbitrary subset of the languages that Prism supports. You can add support for more by including their definitions from the mainprismjs package:
  1. ``` js
  2. import Prism from "prism-react-renderer/prism";
  3. (typeof global !== "undefined" ? global : window).Prism = Prism;
  4. require("prismjs/components/prism-kotlin");
  5. require("prismjs/components/prism-csharp");
  6. ```
How do I use my old Prism css themes?
prism-react-renderer still returns you all proper classNames via the prop getters,
when you use it. By default however it uses its new theming system, which output a
couple of style props as well.
If you don't pass `theme` to the `` component it will default to not
outputting any style props, while still returning you the className props, like
so:
  1. ``` js
  2. <Highlight
  3.   {...defaultProps}
  4.   code={exampleCode}
  5.   language="jsx"
  6.   theme={undefined}
  7. >
  8.   {highlight => null /* ... */}
  9. </Highlight>
  10. ```
How do I prevent a theme and the vendored Prism to be bundled?
Since the default theme and the vendored Prism library in prism-react-renderer
come from defaultProps, if you wish to pass your own Prism library in, and not
use the built-in theming, you simply need to leave it out to allow your bundler
to tree-shake those:
  1. ``` js
  2. import Highlight from "prism-react-renderer";
  3. import Prism from "prismjs"; // Different source
  4. <Highlight Prism={Prism} code={exampleCode} language="jsx">
  5.   {highlight => null /* ... */}
  6. </Highlight>;
  7. ```
You can also import the vendored Prism library on its own:
  1. ``` js
  2. import { Prism } from "prism-react-renderer";
  3. // or
  4. import Prism from "prism-react-renderer/prism";
  5. ```

LICENSE

MIT

Maintenance Status

Active: Formidable is actively working on this project, and we expect to continue for work for the foreseeable future. Bug reports, feature requests and pull requests are welcome.
[maintenance-image]: https://img.shields.io/badge/maintenance-active-green.svg