prodios_lab_assign.mp4
This project implements a simple code editor in React
- Syntax highlighting using PrismJS.
- Supports multiple programming languages.
- Real-time code editing in a
textareaelement with overlayed syntax highlighting.
- React: For building the interactive user interface.
- PrismJS: A library for syntax highlighting.
- HTML Textarea: Used for text input by users.
The main editor consists of two components:
- A transparent
textareafor user input with a white caret for cursor visibility - A
CodeHighlightercomponent that renders the syntax-highlighted code using PrismJS
- A transparent
The editor maintains two states:
code: This Stores the current text content that the user is typingselectedLanguage: Tracks the selected programming language
When the user types in the textarea:
- The
handleChangefunction updates thecodestate - A
useEffecthook triggers PrismJS to re-highlight the code - The
CodeHighlightercomponent re-renders with the updated highlighted code
- The
Synchronization features:
- The textarea and highlighter are overlaid on top of each other
scrollOverlayAndTextAreafunction is used to sync both the scroll for the textarea and the highlighted code- The textarea is set to transparent
Language selection:
- I implemented this so that the Users can switch languages via the
LanguageSelectorcomponent this gives more flexibility to add multi language support
- I implemented this so that the Users can switch languages via the
import{useEffect,useState}from"react";import*asPrismfrom"prismjs";exportdefaultfunctionCodeEditor(){const[code,setCode]=useState<string>("");// Holds the user's input codeuseEffect(()=>{// Highlight code when the `code` state changesPrism.highlightAll();},[code]);consthandleCodeChange=(e: React.ChangeEvent<HTMLTextAreaElement>)=>{setCode(e.target.value);};return(<divclassName="code-editor">{/* Highlighted code overlay */}<preclassName="code-overlay"><codeclassName="language-javascript">{code}</code></pre>{/* User input area */}<textareavalue={code}onChange={handleCodeChange}className="textarea-input"spellCheck="false"/></div>);}functionscrollOverlayAndTextArea(e: React.UIEvent<HTMLTextAreaElement|HTMLPreElement>){consttarget=e.targetasHTMLElement;constsibling=target.nextElementSibling||target.previousElementSibling;if(sibling){(siblingasHTMLElement).scrollTop=target.scrollTop;(siblingasHTMLElement).scrollLeft=target.scrollLeft;}}