Jsx Preview
prompt-kit/jsx-previewFreeComponent
A component for rendering JSX strings as React components, with support for streaming content and automatic tag completion.
Live preview
live · rendered by the registry
Rendered by prompt-kit on their own page — this is the component running, not a screenshot of it.Install it
npx shadcn@latest add https://raw.githubusercontent.com/ibelick/prompt-kit/HEAD/public/c/jsx-preview.jsonSource
1import * as React from "react"2import JsxParser from "react-jsx-parser"3import type { TProps as JsxParserProps } from "react-jsx-parser"45function matchJsxTag(code: string) {6 if (code.trim() === "") {7 return null8 }910 const tagRegex = /<\/?([a-zA-Z][a-zA-Z0-9]*)\s*([^>]*?)(\/)?>/11 const match = code.match(tagRegex)1213 if (!match || typeof match.index === "undefined") {14 return null15 }1617 const [fullMatch, tagName, attributes, selfClosing] = match1819 const type = selfClosing20 ? "self-closing"21 : fullMatch.startsWith("</")22 ? "closing"23 : "opening"2425 return {26 tag: fullMatch,27 tagName,28 type,29 attributes: attributes.trim(),30 startIndex: match.index,31 endIndex: match.index + fullMatch.length,32 }33}3435function completeJsxTag(code: string) {36 const stack: string[] = []37 let result = ""38 let currentPosition = 03940 while (currentPosition < code.length) {41 const match = matchJsxTag(code.slice(currentPosition))42 if (!match) break43 const { tagName, type, endIndex } = match4445 if (type === "opening") {46 stack.push(tagName)47 } else if (type === "closing") {48 stack.pop()49 }5051 result += code.slice(currentPosition, currentPosition + endIndex)52 currentPosition += endIndex53 }5455 return (56 result +57 stack58 .reverse()59 .map((tag) => `</${tag}>`)60 .join("")61 )62}6364export type JSXPreviewProps = {65 jsx: string66 isStreaming?: boolean67} & JsxParserProps6869function JSXPreview({ jsx, isStreaming = false, ...props }: JSXPreviewProps) {70 const processedJsx = React.useMemo(71 () => (isStreaming ? completeJsxTag(jsx) : jsx),72 [jsx, isStreaming]73 )7475 // Cast JsxParser to any to work around the type incompatibility76 const Parser = JsxParser as unknown as React.ComponentType<JsxParserProps>7778 return <Parser jsx={processedJsx} {...props} />79}8081export { JSXPreview }
What it pulls in
npm packages
Files it writes
More from prompt-kit
All 23 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| Chain Of Thoughtchain-of-thought | prompt-kit | Components | Free | 1 dep | |
| Chat Containerchat-container | prompt-kit | Components | Free | 1 dep | |
| Code Blockcode-block | prompt-kit | Components | Free | 1 dep | |
| Feedback Barfeedback-bar | prompt-kit | Components | Free | 1 dep | |
| File Uploadfile-upload | prompt-kit | Components | Free | no deps | |
| Imageimage | prompt-kit | Components | Free | no deps | |
| Loaderloader | prompt-kit | Components | Free | no deps | |
| Markdownmarkdown | prompt-kit | Components | Free | 5 deps · 2 files |
