My favorite music and MDX
Spotify just created a playlist with the most listened songs by me during this 2020, so, I took this opportunity to write a tutorial about MDX and Next.js.
MDX is a Markdown language enhancement, making it more powerful and customizable, because MDX allows rendering React components inside of Markdown files.
This tutorial was written using MDX, so, below, you can see an example of a React component rendered in this post.
https://diegofrayo.dev
Setting up Next.js and MDX
I built this website using Next.js, I'm going to talk about how I configured MDX to create the blog section. To accomplish it, this article posted by Sergio Xalambrí was helpful for me.
First of all, I configured MDX with Next.js and in this link you can check out the instructions, it is really easy to complete it.
Then, I installed the next-mdx-remote package. This package allows rendering MDX files that can be hosted on a remote location, for example, a CMS, a CDN, a database or anywhere. There are other reasons for which it is useful to use this package, in this section of its GitHub repository you can dig deep in the problems that next-mdx-remote solves.
Now, I'm going to explain how to use next-mdx-remote for rendering a blog post in a Next.js page depending on a URL param.
First, I created the function where the property is an array of slugs of all my blog posts that I want to pre-render.
I chose the static-site generation approach because I don't have a lot of pages, probably less than 20 and its content does not change often. I recommend reading more about this topic in this Next.js docs page, its explanation is very clear.
Now, inside of the function, the MDX content of all blog posts is readed. This function only executes at build time, I mean, on the server side. At the moment I store all my blog posts MDX files inside of this website repository. In the future, I could store them on a CMS, for example.
Problem: I can't import components or variables directly inside of MDX files when I use next-mdx-remote to compile them. In this link you can read more about this.
Solution: I had to pass a config object when I invoked the function. The property is an object that contains the data (variables) that I need to use inside of my MDX files.
Finally, this is the component that renders a blog post:
In regards to the MDX components styling, at the beginning I used this Tailwind CSS plugin, but then, I decided don't use it anymore and I built a component with my own styles.
directive allows me to use Tailwind CSS classes within my files.
I used sugar-high for code syntax highlighting:
Final words
I share the URL of this repository in case of you want to see more details about my website and my blog section were implemented. Allright, this is all, thanks for reading.
I share the Spotify playlist for which I wrote down this blog post: