Place google ads in the middle of next-mdx-remote

Place google ads in the middle of next-mdx-remote

Post by: Niraj Dhungana

Posted on: Nov 24, 2021

#MDXRemote# Next JS# Markdown

If you are a programmer and you want to create a blog then nothing is better then Next JS and markdown. If you do so then there is nothing better than next-mdx-remote to render markdown inside your Next JS app.

In the previous post we saw how we can place ads through google adsense inside the Next JS website. Now let's see how we can render google ads in the middle of next-mdx-remote.

Custom component inside MDXRemote

visualizations of injecting custom component to MDX Remote

Here I am going to use the custom Adsense component which I made in the previous post. So, I highly recommend you guys to at least look at the code which we wrote in this post.

If you guys don’t know or it is nice if you already know this thing. The thing is inside next-mdx-remote we can inject custom JSX components.

I hope you already did all the things like serialize and all to render markdown inside MDXRemote. Now I will show you how you can render the Adsense component or your custom adsense component in the middle of other markdown or inside MDXRemote.

1
2
3
4
5
6
7
8
9
import { MDXRemote } from "next-mdx-remote";
export default function PostDetail(){
  return (
    <div className="wrapper">
        // Your custom component should be <Adsense />
        // Or change the component name if you are using different.
        <MDXRemote {...source} components={{ Adsense: AdsenseComponent }} />
    </div>
)}

Now this is how we can inject our custom JSX component inside next-mdx-remote. Let’s create our AdsenseComponent.

1
2
3
4
5
6
7
const AdsenseComponent = (props) => {
  return (
    <div className="YOU_CAN_ADD_STYLES_ALSO(margin/padding)">
      <Adsense {...props} />
    </div>
  );
};

The thing is now if you put <Adsense /> in the middle of your markdown. You will see google ads. Sometimes it takes time or you can check the console. If you don’t have any error related to google adsense. Then you are good to go.

1
2
3
4
5
6
// My sweet markdown with ad
const markdown = `## This is the markdown heading
    I am writing some post here.
    <Adsense />
    Now ^ is the place where you will see google ad.
`

If you have any doubt or suggestion you can DM me on @ndpniraj.