MJML is a markup language created by Mailjet for building responsive HTML emails based on XML.
This library enables MJML integration with React so you can build a responsive HTML email on the fly.
Note that this is a stripped down version of the original https://github.com/wix-incubator/mjml-react which this does not include html-minifier
and mjml2json
to make it work on both Node.js and a web browser.
- Install the dependencies.
yarn add react react-dom
- Install the packages by adding the below to the
dependencies
field in your package.json
"mjml": "https://github.com/taskworld/mjml.git",
"react-mjml": "https://github.com/taskworld/react-mjml.git",
- Create and run the below JavaScript-React file.
import { renderToStaticMarkup } from 'react-dom/server';
import {
Mjml,
MjmlHead,
MjmlTitle,
MjmlPreview,
MjmlBody,
MjmlSection,
MjmlColumn,
MjmlButton,
MjmlImage,
} from "react-mjml";
import mjml2html from 'mjml-browser';
const mjmlString = renderToStaticMarkup(
<Mjml>
<MjmlHead>
<MjmlTitle>Last Minute Offer</MjmlTitle>
<MjmlPreview>Last Minute Offer...</MjmlPreview>
</MjmlHead>
<MjmlBody width={500}>
<MjmlSection fullWidth backgroundColor="#efefef">
<MjmlColumn>
<MjmlImage src="https://static.wixstatic.com/media/5cb24728abef45dabebe7edc1d97ddd2.jpg" />
</MjmlColumn>
</MjmlSection>
<MjmlSection>
<MjmlColumn>
<MjmlButton
padding="20px"
backgroundColor="#346DB7"
href="https://www.wix.com/"
>
I like it!
</MjmlButton>
</MjmlColumn>
</MjmlSection>
</MjmlBody>
</Mjml>
);
const { html, errors } = mjml2html(mjmlString, { validationLevel: "soft" });
And as the result you will get a nice looking email HTML (works in mobile too!)
import {
MjmlHtml,
MjmlComment,
MjmlConditionalComment
} from 'react-mjml/extensions';
<MjmlComment>Built with ... at ...</MjmlComment>
// <!--Built with ... at ...-->
<MjmlConditionalComment>MSO conditionals</MjmlConditionalComment>
// <!--[if gte mso 9]>MSO conditionals<![endif]-->
<MjmlConditionalComment condition="if IE">MSO conditionals</MjmlConditionalComment>
// <!--[if IE]>MSO conditionals<![endif]-->
<MjmlHtml tag="div" html="<span>Hello World!</span>" />
// <div><span>Hello World!</span></div>
We do have also some utils for post processing the output HTML.
Because not all mail clients do support named HTML entities, like '
.
So we need to replace them to hex.
import { namedEntityToHexCode, fixConditionalComment } from "mjml-react/utils";
const html = "<div>'</div>";
namedEntityToHexCode(html);
// <div>'</div>
fixConditionalComment(
"<!--[if mso]><div>Hello World</div><![endif]-->",
"Hello",
"if IE"
);
// <!--[if IE]><div>Hello World</div><![endif]-->