DFP Ads within structured text

We are rendering structured text on our react frontend. We need to push DFP ads within the body content. One ad after first two paragraphs, second ad after first 6 paragraphs and so on. Is it possible to push DFP ads while we are rendering with StructuredText?

We tried -

customRules={[
            renderRule(
              isParagraph,
              ({ adapter: { renderNode }, node, children, key, ancestors }) => {
                if (isRoot(ancestors[0])) {
                  return renderNode('p', { key, className: 'top-level-p-tag' }, children);
                } else {
                  return renderNode('p', { key }, children);
                }
              }
            )
          ]}

But issue is that there are other top level elements too like blockqoute, div etc and also we have custom renderBlock for videos, codeblock etc.

What you could do is to “inject” some additional nodes into the ST document. Example:

const structuredText = graphqlResponse.data.blogPost.content.value;
const topLevelElements = structuredText.document.children;

const dfpNode = { type: 'dfp' };

if (topLevelElements.length >= 2) {
  topLevelElements.splice(2, 0, dfpNode);

  for (let i=7; i < topLevelElements.length; i += 5) {
    topLevelElements.splice(i, 0, dfpNode);
  }
}

Then you can add a render rule for the “virtual” dfp node we injected:

customRules={[
  renderRule(
    (node) => node.type === 'dfp',
    ({ adapter: { renderNode }, node, children, key, ancestors }) => {
      return <div>PLACE THE CODE FOR YOUR DFP HERE</div>;
    }
  )
]}
2 Likes