Let's learn how to embed YouTube videos in your MDX Next.js blog with a Custom Component.
1) YouTube Component
I store all code related to markdown in src/components/mdx
folder.
Let's create a new file called youtube.tsx
in that folder.
Let's understand the above code:
- Takes a required single prop
id
which is the YouTube video ID. - Returns a div with a border and an iframe that embeds the YouTube video.
- The IFrame URL is constructed using the video ID.
Tip
To make the IFrame responsive, add the aspect-video w-full
classnames
to the IFrame within a div.
2) Add Component to MDX Provider
Next, we need to add the YouTube component to the MDX Provider.
I am using Contentlayer for my blog, so I will use the getMDXComponent
function to create the MDX component.
Breakdown of the above code:
- We import the newly created YouTube component.
- We create an MDX component using the
getMDXComponent
function. - We pass the YouTube component to the MDXContent component.
How you use the component may differ based on your MDX setup.
Check below to find documentation for your setup:
3) Usage in MDX
Now you can use the YouTube component in your MDX files.
Above code will create the following result:
Note
You can find the video ID in the YouTube video URL.
eg:https://www.youtube.com/watch?v=dQw4w9WgXcQ
-> ID: dQw4w9WgXcQ