Working as a lead developer for years, I have built dozens of technical documentation sites and developer portfolios.
One feature that always comes up is the need to display code blocks that actually look good and are easy to read.
If you are building a site for a US-based tech startup or a personal blog, a “Hello World” block just won’t cut it.
In this guide, I will show you exactly how I build React code snippet components that provide a premium experience for your users.
The Need for Custom Code Components
Standard HTML <pre> and code tags are functional, but they lack the visual flair needed for modern web applications.
When I am reviewing PRs or documentation, I want to see line numbers, theme support, and clear syntax highlighting.
Method 1: Use React Syntax Highlighter
This is my go-to method when I need to get a project up and running quickly without sacrificing performance.
The react-syntax-highlighter library is incredibly flexible and supports virtualizing long snippets of code.
To start, you will need to install the package via npm:
npm install react-syntax-highlighter
Here is a full example of a component displaying a real-world US Sales Tax calculation logic.
import React from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dracula } from 'react-syntax-highlighter/dist/esm/styles/prism';
const SalesTaxSnippet = () => {
const codeString = `
function calculateTotalWithTax(price, state) {
const taxRates = {
'NY': 0.04, // New York State Tax
'CA': 0.0725, // California Base Tax
'TX': 0.0625 // Texas State Tax
};
const rate = taxRates[state] || 0;
return price + (price * rate);
}
// Example usage for a California resident
const finalPrice = calculateTotalWithTax(100, 'CA');
console.log("Total Price in USD:", finalPrice);
`;
return (
<div style={{ maxWidth: '800px', margin: '20px auto' }}>
<h3>US State Tax Logic</h3>
<SyntaxHighlighter
language="javascript"
style={dracula}
showLineNumbers={true}
>
{codeString}
</SyntaxHighlighter>
</div>
);
};
export default SalesTaxSnippet;You can see the output in the screenshot below.

I prefer using the Prism version of this library because the themes are much more modern and professional.
The “Dracula” theme used here is a favorite among developers in the US, giving your site an instant “pro” feel.
Method 2: Create a Copy-to-Clipboard Component
In my experience, a code snippet is only half as useful if the user can’t easily copy it to their project. Adding a “Copy” button is a small detail that makes a massive difference in user experience.
Here is how I implement a robust snippet component with a functional copy button.
import React, { useState } from 'react';
const CodeSnippetWithCopy = ({ code, language }) => {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(code);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error('Failed to copy!', err);
}
};
return (
<div className="snippet-container" style={{
background: '#1e1e1e',
borderRadius: '8px',
padding: '16px',
position: 'relative',
color: '#fff'
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
marginBottom: '10px'
}}>
<span style={{ fontSize: '12px', color: '#888' }}>{language.toUpperCase()}</span>
<button
onClick={handleCopy}
style={{
background: copied ? '#4caf50' : '#007bff',
color: 'white',
border: 'none',
padding: '5px 10px',
borderRadius: '4px',
cursor: 'pointer'
}}
>
{copied ? 'Copied!' : 'Copy Code'}
</button>
</div>
<pre style={{ margin: 0, overflowX: 'auto' }}>
<code>{code}</code>
</pre>
</div>
);
};
// Implementation using a US Real Estate Mortgage Calculation example
export const MortgageApp = () => {
const mortgageCode = `
const calculateMonthlyPayment = (principal, annualRate, years) => {
const monthlyRate = annualRate / 12 / 100;
const numberOfPayments = years * 12;
// Standard US Mortgage Formula
const monthlyPayment =
(principal * monthlyRate) /
(1 - Math.pow(1 + monthlyRate, -numberOfPayments));
return monthlyPayment.toFixed(2);
};
const myNewHome = calculateMonthlyPayment(450000, 6.5, 30);
console.log(\`Monthly Mortgage: $\${myNewHome}\`);
`;
return (
<div style={{ padding: '20px' }}>
<h2>Mortgage Calculator Logic (US Standard)</h2>
<CodeSnippetWithCopy code={mortgageCode} language="javascript" />
</div>
);
};You can see the output in the screenshot below.

I always use navigator.clipboard because it is the modern standard for browser-based copying.
Notice how the button changes color when clicked; this visual feedback is essential for high-quality UI.
Method 3: Lightweight Component without Libraries
Sometimes, you might be working on a project where you want to minimize the bundle size. In these cases, I skip the external libraries and use a combination of native React and CSS.
While you lose advanced highlighting, you gain significantly in page load speed and control.
import React from 'react';
const SimpleSnippet = ({ title, code }) => {
return (
<div style={{
border: '1px solid #ddd',
borderRadius: '6px',
margin: '20px 0',
fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, monospace'
}}>
<div style={{
backgroundColor: '#f6f8fa',
padding: '10px',
borderBottom: '1px solid #ddd',
fontWeight: 'bold',
fontSize: '14px'
}}>
{title}
</div>
<pre style={{
padding: '15px',
margin: 0,
backgroundColor: '#ffffff',
overflowX: 'auto',
fontSize: '13px',
lineHeight: '1.5'
}}>
<code>{code}</code>
</pre>
</div>
);
};
// US Census Data Fetch Example
export const DataExample = () => {
const censusCode = `
async function getUSCensusData(year) {
const response = await fetch(\`https://api.census.gov/data/\${year}/acs/acs5\`);
const data = await response.json();
// Logic to filter by US State
return data.filter(item => item.region === 'Northeast');
}
`;
return (
<SimpleSnippet
title="Fetching US Census API Data"
code={censusCode}
/>
);
};This approach mimics the look of GitHub’s code blocks, which are very familiar to developers. It works best for short snippets where complex color coding isn’t strictly necessary.
Best Practices for React Code Snippets
Throughout my career, I have found that accessibility is often overlooked in code components.
Always ensure your code blocks have enough color contrast to meet WCAG standards.
[Image showing high contrast vs low contrast code highlighting]
I also recommend adding a “max-height” to your code containers with an “overflow-y: auto” property.
This prevents a very long script from taking up the entire vertical space of your blog post or dashboard.
Choose the Right Method
If you are building a full-scale documentation site, Method 1 with a library like Prism is the way to go.
For a simple blog post where speed is key, Method 3 will keep your site lean and fast.
I personally use Method 2 for most of my client work because the “Copy” feature is a non-negotiable for me.
In this tutorial, we looked at three different ways to create a React code snippet component.
Building these components yourself gives you the flexibility to match your brand’s unique design language.
You may also like to read:
- How to Build a React File Explorer Component
- React Context in Functional Components
- How to Refresh or Reload a Component in React
- How to Convert React Component to Web Component

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.