To create a React component with TypeScript that displays Go code with line numbers, syntax highlighting, and custom styles for specified line ranges, follow these steps:
Step 1: Install Dependencies
Install the necessary packages for syntax highlighting and React integration:
npm install prism-react-renderer prismjs
Step 2: Import Required Modules
Import the Go language syntax for Prism and the Code component from prism-react-renderer:
import React from 'react';
import { Code } from 'prism-react-renderer';
import 'prismjs/components/prism-go';
Step 3: Define Props Interface
Define the props for the component, including the code lines and line ranges with styles:
interface LineRange {
start: number;
end: number;
style: React.CSSProperties;
}
interface CodeDisplayProps {
codeLines: string[];
lineRanges: LineRange[];
}
Step 4: Create the CodeDisplay Component
Implement the component using the Code component from prism-react-renderer, applying styles based on line ranges:
const CodeDisplay: React.FC<CodeDisplayProps> = ({ codeLines, lineRanges }) => {
const code = codeLines.join('\n');
return (
<Code
code={code}
language="go"
showLineNumbers
lineProps={(lineIndex) => {
const lineNumber = lineIndex + 1;
const styles: React.CSSProperties = {};
lineRanges.forEach((range) => {
if (lineNumber >= range.start && lineNumber <= range.end) {
Object.assign(styles, range.style);
}
});
return { style: styles };
}}
/>
);
};
export default CodeDisplay;
Step 5: Usage Example
Use the component in your application with sample data:
import CodeDisplay from './CodeDisplay';
const App = () => {
const codeLines = [
"package main",
"import \"fmt\"",
"func main() {",
" fmt.Println(\"Hello, World!\")",
"}"
];
const lineRanges = [
{ start: 3, end: 5, style: { backgroundColor: '#f0f0f0', color: 'green' } },
{ start: 1, end: 1, style: { backgroundColor: 'lightblue' } }
];
return <CodeDisplay codeLines={codeLines} lineRanges={lineRanges} />;
};
export default App;
Explanation:
- Dependencies: The
prism-react-renderer and prismjs packages handle syntax highlighting and React integration.
- Props Interface: The
LineRange interface defines the start, end, and style for each line range.
- Component Logic:
- Code Joining: The
codeLines array is joined into a single string for the Code component.
- Line Styling: The
lineProps function checks each line's number against the provided ranges and applies the corresponding style.
- Usage: The component is rendered with code lines and line ranges, applying styles to specified lines.
This component efficiently displays Go code with line numbers, syntax highlighting, and custom styles for specified ranges.