Is it possible to render a script that has been inserted within the body tag (using setPostBodyComponents) only in certain pages other than all of them ?
Any ideas if this would be possible ?
As you can see in gatsby-ssr-js
docs, onRenderBody
exposes a bunch of props
where there's a pathname
.
pathname
{string}The pathname of the page currently being rendered.
That said, you can try something like:
const React = require("react")
exports.onRenderBody = ({ setPostBodyComponents, pathname }) => {
const SCRIPT_PAGES = ['/page-1', '/page-2'];
if(SCRIPT_PAGES.includes(pathname)){
setPostBodyComponents([
<script dangerouslySetInnerHTML={{ __html:`your script here`}} />,
]);
}
};
In that case, your SCRIPT_PAGES
will hold the pages where the script will be inserted. Using that approach, you can tweak it as you want.