A react package to generate HTML for conversion to Email or PDF from shared components
npm install react-to-html> Inspired by react-email from @zenorocha & @bukinoshita.
``bash`nnpm
npm i react-to-htmlpnpm
pnpm add react-to-htmlyarn
yarn add react-to-html
ts
// tohtml.config.ts
exports.settings = {
content: [
{
path: './components/Example.tsx',
props: {
foo: "bar",
},
}
],
globalStyles: './app/globals.css',
pageHeight: '297mm', // A4
pageWidth: '210mm', // A4
outputDir: './output',
outputFormat: 'pretty | minified',
};
`
$3
To run react-to-html simply run the command or add a script in your own packages.json.
`bash
npm
npm build:html
pnpm
pnpm build:html
yarn
yarn build:html
`Example component
Below is an example component using tailwind and imported icons from Lucide. > [!IMPORTANT]
> You cannot use local imports for components you wish to convert to HTML. You should validate your data before passing it as props.
`tsx
import React from "react";
import { ShoppingCartIcon } from "lucide-react";interface ExampleProps {
foo: string;
}
const Example = ({foo}: ExampleProps) => {
return (
Yout items
{foo}
- Item 1
- Item 2
)
}export default Example;
`
In this example, foo will return the string bar when converted to HTML.> [!TIP]
> You can declare functions, interfaces & types and components in your component.
$3
The example above shows you how to convert the prop
foo which is of string valu, however you may need to work with an object suchg as item. To do this you can give your component an additional prop for example isStatic of type boolean and use conditional rendering`typescript
// Example.tsx
interface Seller {
name: string;
website: string;
};interface ExampleProps extends Seller {
seller: Seller;
isStatic: boolean;
}
const Example = ({
seller,
isStatic = true // default
}: ExampleProps) => {
function replaceWith(key: any, actualValue: any) {
return isStaticMode ?
${key} : actualValue;
} return (
Seller
{replaceWith("foo", seller?.name)}
{replaceWith("bar", seller?.website)}
)
}
`Generate PDF from HTML
If you are converting yout components to HTML so they can be later converted to PDF, it's recommended to use a package like Puppeteer.Puppeteer can handle most modern CSS such as flex and grid which seem to be a common frustration with many packages.
Using a decorator
Inspired by Storybook's decorators, react-to-html provides you with a decorator as a way to wrap your componment inside additional code. By default this will wrap your component in a standard HTML page and insert your styles with the styles tags.
$3
`typescript
// tohtml.config.js
exports.settings = {
decorator: (content, styles) =>
}
``