Skip to content

quaos/deno-html-react-transformer

Repository files navigation

Deno HTML to React Transformer

Tool for Transforming HTML/DOM to React element in Deno

WARNING

Do not forget to enforce XSS protection with libraries like DOMPurify, even thought this module provides some basic protections such as blocking <script> and <iframe> tags by default!

Usage

import {
  Transformer, TransformContext, TransformerEvent,
} from "https://deno.land/x/[email protected]/mod.ts";

const html = `<div>
  <h1>Test</h1>
  <p>&nbsp;&nbsp;Test HTML content</p>
</div>
`;

export const App = ({ }) => {
  const Renderer = React.useMemo(() => {
      const transformer = new Transformer({
        // Optional (default: false)
        dangerouslyAllowScripts: false,
        // Optional (default: false)
        dangerouslyAllowIFrames: false,
        // Optional (default: undefined)
        maxDepth: 64,
      });
      transformer.on(TransformerEvent.Element, (ctx: TransformContext) => {
        if (ctx.component === "a") {
          // If using React Router lib:
          ctx.component = Link;
          let { href } = ctx.props;
          ctx.props = {
            to: href,
            onClick = (evt) => interceptLinkClick(evt, ctx),
          };
          ctx.children = (
            <span>External link: {ctx.children}</span>
          );
        }
      });
      transformer.on(TransformerEvent.Errors, (ctx: TransformContext) => {
        ctx.errors.forEach(console.error);
      });

      /**
       * Supply your own React instance here
       * if you face "Invalid hook call" or other errors
       * relating to redundant React instances 
       */
      return transformer.getComponent(React);
  });

  return (
    <Renderer source={html} />
  )
} 

Dependencies

  • Deno version ^1.32
  • React version ^18.0
  • deno_dom (for testing from CLI)

Testing

yarn

yarn test

npm

npm run test

Running Example

yarn

yarn example:build && yarn example:run

npm

npm run example:build && npm run example:run

About

Tool for Transforming HTML/DOM to React element in Deno

Resources

Stars

Watchers

Forks

Packages

No packages published