Embedding any third-party JavaScript into a React-based framework requires you to create a script and append it to the element in your layout component.
If you’re reading this post, you may be taking the framework-first learning approach and are unfamiliar with loading the script without importing a component or a package.
This component should work with most of the React-based frameworks. Here is the carbon.tsx
component that you can also find in this CodeSandBox project.
import React, { useEffect } from "react";
import { useRouter } from "next/router";
const CarbonAds = () => {
const router = useRouter();
useEffect(() => {
const isCarbonExist = document.querySelector("#carbonads");
if (!!isCarbonExist) {
_carbonads.refresh();
return;
}
const script = document.createElement("script");
script.src =
"//cdn.carbonads.com/carbon.js?serve=CVAIKKQM&placement=carbonadsnet";
script.id = "_carbonads_js";
script.async = true;
document.querySelectorAll("#carbon-container")[0].appendChild(script);
}, [router.asPath]);
return <div id="carbon-container"></div>;
};
export default CarbonAds;
Replace the value of script.src
with the ad tag found on your dashboard. The component doesn’t do anything fancy. It simply creates an empty div
container with carbon-container
as the class name where we append them after the component is successfully mounted. It uses [router.asPath]
as the dependency to refresh the ad when the #carbonads
element exists on the page already.
Dealing with Duplicate Ads
One of the common problems you often see with implementing Carbon Ads component with this method is seeing duplicate ads. It happens because reactStrictMode
is enabled by default when you’re working with newer React projects. If you’re using Next.js, you can turn it off in next.config.js
to prevent duplicate ads from appearing.
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
};
module.exports = nextConfig;