Set up an AMP HTML page with react-amphtml
masterTo generate a valid AMP HTML page, you must include specific boilerplate and the scripts required by the AMP directives you use. The react-amphtml/setup module provides the necessary tools to automate this.
Workflow
- Initialize
AmpScriptsto track required scripts. - Wrap your body content in
AmpScriptsManagerto collect the necessary scripts. - Use
headerBoilerplateto generate the required<head>content. - Use
Amp.Htmlto structure the document. - Use
ampScripts.getScriptElements()to inject the collected scripts into the<head>.
import * as Amp from 'react-amphtml';
import { AmpScripts, AmpScriptsManager, headerBoilerplate } from 'react-amphtml/setup';
import { renderToStaticMarkup } from 'react-dom/server';
const ampScripts = new AmpScripts();
// 1. Prepare body content with Script Manager
const bodyContent = renderToStaticMarkup(
<AmpScriptsManager ampScripts={ampScripts}>
<div>
<Amp.AmpImg
specName="default"
src="/"
width={0}
height={0}
layout="responsive"
alt="test"
/>
<Amp.AmpAccordion />
</div>
</AmpScriptsManager>
);
// 2. Assemble the full HTML document
/* eslint-disable react/no-danger */
const html = renderToStaticMarkup(
<Amp.Html>
<head>
{headerBoilerplate('/')}
<title>react-amphtml</title>
{ampScripts.getScriptElements()}
</head>
<body dangerouslySetInnerHTML={{ __html: bodyContent }} />
</Amp.Html>
);
/* eslint-enable */
const htmlPage = `<!doctype html>${html}`;import * as Amp from 'react-amphtml';
import { AmpScripts, AmpScriptsManager, headerBoilerplate } from 'react-amphtml/setup';
const ampScripts = new AmpScripts();
const bodyContent = renderToStaticMarkup(
<AmpScriptsManager ampScripts={ampScripts}>
<div>
<Amp.AmpImg specName="default" src="/" width={0} height={0} layout="responsive" alt="test" />
<Amp.AmpAccordion />
</div>
</AmpScriptsManager>
);
const html = renderToStaticMarkup(
<Amp.Html>
<head>
{headerBoilerplate('/')}
<title>react-amphtml</title>
{ampScripts.getScriptElements()}
</head>
<body dangerouslySetInnerHTML={{ __html: bodyContent }} />
</Amp.Html>
);