Created
November 14, 2025 12:25
-
-
Save TheWebDevel/8b59966af939091ab3b71870c47ec0e4 to your computer and use it in GitHub Desktop.
prettier-html-formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useEffect, useState } from "react"; | |
| import prettier from "prettier/standalone"; | |
| import { Prism as SyntaxHighlighter } from "react-syntax-highlighter"; | |
| import { oneLight } from "react-syntax-highlighter/dist/esm/styles/prism"; | |
| const sampleHtml = ` | |
| <div class="card"><h1>Hello</h1><p>World</p><span>Test</span></div> | |
| `; | |
| export default function HtmlBeautifyViewer({ rawHtml = sampleHtml }) { | |
| const [prettyHtml, setPrettyHtml] = useState(""); | |
| const [safeHtml, setSafeHtml] = useState(""); | |
| useEffect(() => { | |
| async function formatHtml() { | |
| try { | |
| // ALWAYS convert to string | |
| const safe = | |
| typeof rawHtml === "string" | |
| ? rawHtml | |
| : rawHtml == null | |
| ? "" | |
| : String(rawHtml); | |
| setSafeHtml(safe); | |
| // DYNAMICALLY load plugins (Fixes .match error everywhere) | |
| const [htmlPlugin, babelPlugin, estreePlugin] = await Promise.all([ | |
| import("prettier/plugins/html.js"), | |
| import("prettier/plugins/babel.js"), | |
| import("prettier/plugins/estree.js"), | |
| ]); | |
| const formatted = await prettier.format(safe, { | |
| parser: "html", | |
| plugins: [htmlPlugin, babelPlugin, estreePlugin], | |
| htmlWhitespaceSensitivity: "ignore", | |
| }); | |
| setPrettyHtml(formatted); | |
| } catch (err) { | |
| console.error("FORMAT ERROR:", err); | |
| setPrettyHtml(rawHtml); | |
| } | |
| } | |
| formatHtml(); | |
| }, [rawHtml]); | |
| return ( | |
| <div style={{ display: "flex", gap: "20px", padding: "20px" }}> | |
| {/* Syntax Highlighted HTML */} | |
| <div style={{ width: "50%" }}> | |
| <h3>Beautified HTML</h3> | |
| <div style={{ maxHeight: "80vh", overflow: "auto" }}> | |
| <SyntaxHighlighter language="html" style={oneLight} showLineNumbers> | |
| {prettyHtml} | |
| </SyntaxHighlighter> | |
| </div> | |
| </div> | |
| {/* Rendered Preview */} | |
| <div style={{ width: "50%", border: "1px solid #eee", padding: "10px" }}> | |
| <h3>Rendered Preview</h3> | |
| <div dangerouslySetInnerHTML={{ __html: safeHtml }} /> | |
| </div> | |
| </div> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment