You build add code snippets in React by treating a snippet as data, not markup: store the code string, language, and optional title in a props object, render them through a component, and add copy, syntax highlighting, and multi-snippet grouping as separate layers you can opt into. The key condition is preventing React and JavaScript from interpreting the code before it reaches the DOM. Keep the code as a plain string and let the browser display it as text. Everything else, from copy-to-clipboard behavior to line numbers to theme switching, builds on that foundation.
This guide walks through a working implementation in order, then covers the trade-offs you'll hit when snippets get numerous, long, or dynamic.
Prerequisites Before You Start
You need a React project that renders with a modern toolchain. Any of these work: Vite with the React template, Next.js App Router, or Create React App. The examples assume React 18 or later and functional components with hooks. You don't need TypeScript, but the optional type sketch at the end shows how to make props safer.
You also need to decide two things before writing code:
Scope: Is a snippet just a string, or does it need a title, language label, and source filename? Start with title and language; add more only when a real screen needs it. Content source: Are snippets authored in the same file as the component that shows them, imported from a content module, or fetched from an API? Hardcoded strings are fine for a handful. A separate module of snippet objects scales better and lets you test them independently.
Finally, confirm how your app handles clipboard permissions if you plan to support copy. The Clipboard API requires a secure context: HTTPS in production, or localhost during development. That detail trips people up when they test on a phone against a dev machine's LAN address over plain HTTP.
Step 1: Render a Raw Code String Safely
The single most common failure in React snippet components is writing the code directly into JSX. Curly braces in JavaScript become JSX expressions, angle brackets become elements, and your snippet renders as broken UI or a syntax error.
Here's the wrong instinct:
The right approach is to wrap the code in a JavaScript string, then render the string. React escapes string children automatically, so the browser shows the literal characters rather than parsing them.
Use a template literal for the snippet so multi-line code stays readable:
Note the escaped backticks and dollar signs inside the template literal. If your snippet itself contains template literals, you have three options: escape them as shown, store the snippet in a .txt or .md file and import it as a raw string (Vite supports ?raw imports; bundlers differ), or move snippets into JSON where escaping rules are simpler. Pick one convention early, because mixing them is where maintenance pain starts.
Check your success: render the component with code that includes <, >, {, }, backticks, and &&. If the output shows those characters literally instead of throwing or collapsing, the escaping layer is correct. If you see an empty box or a React error about objects not being valid children, you've passed something other than a string.
Step 2: Add Structure With Title, Language, and a Semantic Wrapper
A bare works for one snippet. A library needs a consistent shell: a heading area, a language badge, and a scrollable code region. Keep the wrapper semantic so screen readers and keyboard users can navigate it.
Two deliberate choices here. tabIndex={0} on the makes the scrollable region focusable, so keyboard users can scroll long code with arrow keys; a scroll container that can't receive focus is a known accessibility gap. And / pairs the label with the content semantically, which is more robust than a stack of unlabeled divs.
Add CSS for horizontal overflow rather than letting long lines wrap mid-token:
Check your success: paste a 200-character single line into a snippet. The block should scroll horizontally without breaking the page layout, and tabbing to it should show a visible focus ring. If the line wraps and breaks indentation, your overflow-x isn't applying to the right element.
Step 3: Implement Copy-to-Clipboard With Real Feedback
Copy is the feature users actually judge. The modern path is navigator.clipboard.writeText, which returns a promise. Older fallback approaches using a hidden textarea and document.execCommand("copy") still appear in tutorials, but that API is deprecated; don't build new code around it.
Three details matter more than they look:
1: Reset the label after a short delay. A permanently changed "Copied" label leaves the user unsure whether the button still works. Two seconds is a reasonable window. 2: Handle the rejection. Clipboard writes fail when the document isn't focused, when permission is denied, or in insecure contexts. Swallowing the error silently produces a button that appears to work and doesn't. 3: Clear the timeout on unmount. Otherwise a fast navigation triggers a state update on an unmounted component. React 18 no longer warns loudly about this, but the timer still leaks.
Place the button in the header area rather than floating over the code, so it doesn't cover the first line of content on narrow screens.
Check your success: copy a snippet, paste into a plain text editor, and confirm indentation and line breaks survive. Then open the page over http:// on a non-localhost address and confirm you see the "Copy failed" state instead of a silent no-op.
Step 4: Add Syntax Highlighting Without Breaking the String Model
Highlighting transforms a plain string into an array of tokens, each wrapped in a styled span. You have three realistic routes, and they differ in bundle cost, flexibility, and runtime risk.
Route A: A tokenizer library at runtime. Libraries such as Prism or highlight.js take the code string at render time and return HTML or a token tree. They're easy to start with and support many languages. The cost is bundle size and processing time on every render, which you should memoize. Prism's React integrations vary; many inject HTML via dangerouslySetInnerHTML, which reintroduces exactly the injection surface you avoided in Step 1.
Route B: A React-native highlighter. Components built specifically for React return an element tree instead of an HTML string. This keeps React in charge of escaping and avoids dangerouslySetInnerHTML entirely. The trade-off is fewer supported languages and sometimes slower updates on very large snippets.
Route C: Highlight at build time. For documentation sites with static snippets, run a tokenizer in a build step and store the token output (or pre-rendered HTML) alongside the content. Runtime cost drops to near zero. This is the best fit when snippets don't change per user, and the worst fit for a live code editor.
If you choose Route A or B, memoize the highlighting call so typing in an unrelated input doesn't retokenize every snippet on the page:
tokenize and renderToken stand in for whichever library you pick; the memoization pattern is the part that translates across them.
A failure case worth knowing: highlighting libraries occasionally mis-tokenize code with embedded template literals or JSX. The output looks subtly wrong (a string colored as an operator, for instance) but never crashes. Don't assume highlighting correctness means content correctness; spot-check snippets with nested quotes after you switch libraries or upgrade versions.
Check your success: render the same snippet twice with the same props and confirm the highlight function runs once, not twice, using a console counter. Then verify the rendered DOM text, with tags stripped, exactly equals the original string. If characters are missing, your tokenizer is dropping whitespace or newlines.
Step 5: Compose Multiple Snippets, Tabs, and Fill-in-the-Blank Variants
Real docs rarely show one snippet in isolation. You'll want grouped examples (JavaScript and TypeScript versions side by side), tabbed variants, or a snippet with placeholders the reader is meant to replace.
For tabs, keep state in a parent and pass the active snippet down; don't give each tab its own copy button that copies the wrong content.
For fill-in-the-blank snippets, a useful pattern is a small template with named placeholders and a render step that highlights the placeholder tokens. Keep the copy action copying the template as-is unless you also give the user inputs to substitute values; a copy button that silently strips placeholders confuses readers who paste and get errors.
If you need line numbers, generate them from the code string's line count and render them in a separate non-selectable column beside the . Don't put line numbers inside the element, because they'll be included when the user selects text manually.
Step 6: Handle Dynamic, Long, and User-Supplied Code
Three situations break naive implementations.
Dynamic snippets fetched at runtime. If code arrives from an API, treat it as untrusted. Because you're rendering it as text, you're largely protected from script injection, but be careful if you switch to dangerouslySetInnerHTML for highlighting: sanitize the highlighted output or use a token-tree renderer. Never pass fetched code through eval, new Function, or a framework that compiles it.
Very long snippets. A 2,000-line file in one stresses layout and highlighting. Options include collapsing with a "show more" toggle at a fixed max-height, virtualizing the lines (complex, but libraries exist), or linking to a full-file view. For most documentation, a max-height with overflow-y: auto is enough and costs nothing.
Snippets that must stay copy-perfect. Watch for anything that reformats whitespace: CSS white-space settings that collapse spaces, editor auto-formatting that reformats template literals, and minifiers that might touch string content if you're careless. Add a test that asserts the rendered text content equals the source string for each snippet in your registry.
Check your success: load a snippet over the max-height and confirm it scrolls vertically with focus on the . Then run your text-equality test on every snippet in the registry; a single failure usually means an escaping mistake introduced during editing.
Trade-offs: Runtime Highlighting vs Build-Time vs No Highlighting
| Approach | Bundle cost | Update speed | Best for | Main drawback |
|---|---|---|---|---|
| No highlighting | None | Instant | Tiny sites, one-offs | Harder to read complex code |
| Runtime, HTML-string library | Moderate to large | Depends on snippet size; memoize | Apps with many languages | Needs sanitization if injecting HTML |
| Runtime, token-tree component | Moderate | Fast for short snippets | React-first codebases | Fewer language options |
| Build-time tokenization | None at runtime | Instant | Static docs and blogs | Not suitable for user-supplied code |
The mismatch to watch: comparing byte counts between these approaches across different languages and markup formats is misleading. A library that ships 40 languages minified may be smaller for your actual bundle after tree-shaking narrows it to three. Measure your built bundle with your chosen languages, not the library's headline number.
My recommendation for most React apps: start with no highlighting, add a token-tree component when readers complain, and move to build-time only when snippets stop changing at runtime. That sequencing avoids committing to a library before you know whether you need it.
Making the Snippet Library Type-Safe and Reusable
A small prop contract keeps the component honest as it grows. In TypeScript, that looks like this:
Two refinements pay off in review. First, validate at the boundary: if snippets come from a content module, a runtime check that code is a string catches copy-paste errors where someone pastes a JSX element instead of a string. Second, centralize the registry in one module and export both the components and the raw strings, so tests and copy handlers read from the same source of truth.
When a snippet needs a version-specific import path or API shape, store the version in the snippet's metadata rather than duplicating the component. That way a single copy button and one highlighting path serve every variant, and you avoid the drift where one copy of a snippet gets an update and another doesn't.
Testing and Failure Modes to Check Before Shipping
A short checklist catches the failures that survive visual inspection:
Escaping: snippets containing <, {, and backticks render literally. Covered in Step 1. Copy fidelity: pasted output matches the source string character for character, including trailing newlines. Some editors strip a final newline on paste; decide whether that's acceptable and document it. Clipboard failure path: the error label appears when the API rejects. Test by denying clipboard permission in the browser. Keyboard access: the scroll region is focusable and the copy button is reachable and activatable with Enter and Space. Unmount safety: navigating away immediately after clicking copy produces no console warnings about state updates after unmount. Large snippet behavior: vertical scroll engages, and highlighting doesn't freeze the tab on a multi-hundred-line example.
Each of these corresponds to a specific earlier step, so a failure tells you which layer to reopen rather than sending you through the whole component again.
If you're building this for a shared component library, the stop condition is different from a one-off page: once other teams depend on the component, prop changes and copy behavior become a compatibility contract. At that point, adding a versioned prop contract and a changelog is worth the overhead. Until then, keep the component small and resist adding formatting options that no screen currently uses.