Netlify CMS & Next.js Series - Allow CMS Users to edit Markdown

You'll sometimes want CMS users to have more control over the text content so they can style it any way they like. To allow this Netlify CMS has the markdown widget but you'll then need to render that content in JSX.

Let's change the Hero title to markdown so users can style the title how they like.

edit-markdown-1.png

We'll need to change the widget type to 'markdown' in the config.yml file.

filename: public/config.yml

...
fields:
  - { label: "Heading", name: "heading", **widget: "markdown"** }
  - { label: "Detail", name: "detail", widget: "markdown" }
...

Markdown Widget

This widget is described on the Netlify CMS sites as:

The markdown widget provides a fully-fledged text editor - which is based on slate - that allows users to format text with features such as headings and blockquotes.

To render markdown widgets items we'll be using markdown-to-jsx "The most lightweight, customizable React markdown component."

markdown-to-jsx

Add the component to our project using the command:

yarn add markdown-to-jsx

NOTE: I recommend you check out the markdown-to-jsx options.overrides its an amazing feature that makes it possible to dynamically render almost any React component.

Markdown wrapper

markdown-to-jsx has lots of options that we may want to set. We don't want to have to set these options every time we use the component so we'll wrap to component allowing us to set the options in a single place.

filename: components/Markdown.tsx

import React from "react";
import MarkdownToJSX from "markdown-to-jsx";

export const Markdown: React.FC = ({ children }) =>
  children ? <MarkdownToJSX>{String(children)}</MarkdownToJSX> : null;

Render the Markdown

We can now use the Markdown wrapper component to render user-editable markdown on our pages:

filename: pages/index.tsx

...
import { Markdown } from "../components/Markdown";
...

...
<h2 className="mt-1 text-4xl tracking-tight leading-10 font-extrabold text-gray-900 sm:leading-none sm:text-6xl lg:text-5xl xl:text-6xl">
    <Markdown>{hero.heading}</Markdown>
</h2>
...

We can use html snippets in our markdown to render the Hero title with a custom colour section:

<span className="text-indigo-600">top tech companies</span>
filename: content/index.md

---
hero:
  detail: Work with professional software developers and scrum masters to make your 
    project a reality. Minimise risk, cost and time compared to traditional 
    development. Have complete control and insight into your development process, just 
    like the best tech companies in the world.
  heading: Build software like the world's <span className="text-indigo-600">top tech companies</span> do
  image: /images/hero.jpg
---

This gives us a splash of colour in the Hero title but more importantly, the user is now free to style the title as they like 🙂

edit-markdown-2.png

No Comments Yet