React Refractor - Syntax Highlighter

4.0.0 · active · verified Sun Apr 19

react-refractor is a lightweight React component for syntax highlighting code snippets, acting as a thin wrapper around the `refractor` library. `refractor` itself is a virtual DOM implementation of `Prism.js`, allowing for efficient updates and server-side rendering without direct DOM manipulation. The current stable version is v4.0.0, which dropped Node.js 18 support and upgraded to `refractor` v5. The library maintains a moderately active release cadence, with several minor and major versions released within the last year. A key differentiator is its VDOM-based approach, which makes it performant and flexible for React environments but also means it's incompatible with `Prism.js` plugins. Developers must explicitly import and register specific language syntaxes from `refractor` to keep bundle sizes small, and styling is left to the developer, often by importing `Prism.js` themes. It requires React 18+ and is ESM-only since v3.0.0.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to install `react-refractor`, register multiple language syntaxes (JavaScript, PHP, CSS) from `refractor`, and render code snippets using the `Refractor` component. It highlights the explicit language registration process and the component's basic usage with `language` and `value` props.

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Refractor, registerLanguage } from 'react-refractor';

// Import desired languages from 'refractor' and register them
import js from 'refractor/lang/javascript';
import php from 'refractor/lang/php';
import css from 'refractor/lang/css';

registerLanguage(js);
registerLanguage(php);
registerLanguage(css);

// A simple PrismJS theme can be included for basic styling
// This would typically be imported from a CSS file like: import 'prismjs/themes/prism-dark.css';
// For demonstration, we'll just show the component usage.

function App() {
  const jsCode = `
const greet = (name) => {
  console.log('Hello, ' + name + '!');
};
greet('World');
`;

  const phpCode = `
<?php
  $name = "PHP";
  echo "Hello, " . $name . "!";
?>
`;

  return (
    <div>
      <h2>JavaScript Example</h2>
      <Refractor language="javascript" value={jsCode} />

      <h2>PHP Example</h2>
      <Refractor language="php" value={phpCode} />

      <p>Note: Stylesheets are not automatically handled; apply your own Prism.js-compatible theme.</p>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root') || document.createElement('div'));
root.render(<App />);

view raw JSON →