react-email-dynamic
v1.1.0
Published
Render dynamic React Email templates at runtime.
Downloads
70
Readme
React Email Dynamic
Introduction
React Email Dynamic is a library that allows for runtime rendering of templates written with React Email components and JSX. This can be useful in scenarios where you want to keep your templates in a database or make them editable by non-developers. It uses SWC to compile the JSX and React Email itself to render the components.
Installation
NPM
npm install react-email-dynamic
PNPM
pnpm install react-email-dynamic
Yarn
yarn add react-email-dynamic
Usage
import { render } from 'react-email-dynamic';
const template = `
<Html lang="en">
<Text>Hello, World!</Text>
<Hr />
<Button href="https://example.com">Click me</Button>
</Html>
`;
(async () => {
const html = await render(template);
const plainText = await render(template, {
reactEmailRenderOptions: {
plainText: true,
},
});
})();
API
render(template: string, options?: RenderOptions): Promise<string>
Renders the given template string into an HTML string asynchronously.
renderSync(template: string, options?: RenderOptions): string
Renders the given template string into an HTML string synchronously. Use in environments where asynchronous calls are not possible or desired.
RenderOptions
reactEmailRenderOptions?: @react-email/render.Options
: Options passed to the React Email's render function. Pass{ plainText: true }
to render plain text instead of HTML.scope?: Record<string, any>
: An object serving as the scope for the template. Enables the passing of data and/or custom components. See the Advanced Usage section for more information.swcOptions?: swc.Options
: Configuration options for the SWC compiler, allowing adjustments to the JSX parser and other compile-time settings.
Security
This library does not perform input validation or sanitization. Passing user input directly to the template string or the scope object can lead to arbitrary code execution and XSS (Cross-Site Scripting) attacks. Only allow a trusted source to modify the template. If you need to pass user input to the template via the scope
object, ensure each value is sanitized. Possible solutions include using libraries such as DOMPurify or sanitize-html.
Advanced Usage (custom components and data)
You can pass custom components and data into the template by using the scope
option. The values can be any valid React component or data type. This can lead to vulnerabilities, so check the Security section before using this feature.
import { render } from 'react-email-dynamic';
const template = `
<Html lang="en">
<Heading>{message}</Heading>
<CustomComponent />
</Html>
`;
const scope = {
message: 'Hello, World!',
CustomComponent: () => <Text>Custom component</Text>,
};
(async () => {
const html = await render(template, { scope });
})();
License
This project is licensed under the MIT License - see the LICENSE file for details.