How to Add Advert Scripts to a React Website

Last Updated: scripts added to React website

I was recently asked to add a ad script onto a clients React based website, as they were moving from one ad provider to another.

My concern was needs a script adding to the website, which then injects its own code. Then once this is complete it also requires individual scripts in each location that an advert is to be shown. do not provide a React package themselves to help publishers add the script (missed opportunity I feel). So there are a number of suggested solutions online. After trying several, this is the solution I found works the best (altered to my needs).


Adding the main JS script to the head

Firstly to add the main body script to a site we need to use Helmet from ‘react-helmet’ Like so:

import React from "react";
import { Helmet } from "react-helmet";
const myReactPage = () => (
  <div className="application">
      <script type="text/javascript">
        window._mNHandle = window._mNHandle || {}; window._mNHandle.queue =
        window._mNHandle.queue || []; medianet_versionId = "YOUR VERSION ID";
        src=" CUSTOMER ID"
    {/* Rest of page */}

(Make sure to update the script to use your IDs.)

Adding ads to each location

Then to allow us to simply re-use the Ad component throughout the site easily, make a component for where we want the ads to show up.

import React, { useEffect } from "react";

const MediaNetAd = ({ id, size }) => {
  useEffect(() => {
    if (typeof window !== "undefined") {
      try {
        window._mNHandle.queue.push(function () {
          window._mNDetails.loadTag(id, size, id);
      } catch (error) {}
  }, [id, size]);

  return (
    <div className="mediaAdWrapper">
      <div id={id} />

export default MediaNetAd;

I added a wrapper around the div that holds the id. This allow me to control the spacing between the adverts and my content using CSS.

This component is then used like this:

const PageOfApp = () => (
  <div className="content">
    {/* Something here */}
    <MediaNetAd id="YOUR ID" size="300x250" />
    {/* Something here */}

Depending on how much control you wanted, you could move the ID into the component so you only need to pass in the size prop.

I hope this helps!

Related Posts