So I've been working on porting this blog theme (Casper) over to a Sitecore JSS site, which I'll be talking more about in the future but there's really something I couldn't leave behind: Markdown. I love the Ghost markdown editor.

I thought about keeping Ghost up and running and just importing new posts with Data Exchange Framework (DEF) but that honestly felt like cheating. I just wanted a simple editor where I could write markdown and preview the output in some way. Here's what I came up with:

Markdown Field in Experience Editor

Luckily we're writing in Javascript with Sitecore JSS and have a lot of flexibility here. This component was written with Svelte but all the same principles apply to any other framework. By now we've all worked with the built in fields with Sitecore JSS to render various field types but we can also implement our own field components that render content in any way we want it and instead of using those built in components, we'll use our own.

For this markdown component, we'll just define a simple multi line text field because markdown is just text. No need to reinvent the wheel with a custom Sitecore field here. So our component will look like this:

Jumbotron.sitecore.js

export default function(manifest) {
  manifest.addComponent({
    name: 'Jumbotron',
    icon: SitecoreIcon.DocumentTag,
    fields: [
      { name: 'heading', type: CommonFieldTypes.SingleLineText },
      { name: 'text', type: CommonFieldTypes.MultiLineText },
    ],
  });
}

Where text is the field that is going to be the field we want to use with markdown. After that we can import the implementation of the markdown field. This component relies on marked to render the markdown to HTML.

MarkdownField.svelte

The component itself renders the layout service editable fields in a hidden div and then updates the hidden Experience Editor fields itself when the textarea containing the markdown changes. There's likely much better ways to accomplish this but this seems to work pretty well.

Usage of this component just involves importing the MarkdownField component and then utilizing it to render the field:

Jumbotron.svelte

<script>
  import MarkdownField from './MarkdownField.svelte';

  export let fields = null;
</script>

<section class="jumbotron text-center">
  <div class="container">
    <p class="lead text-muted">
      <MarkdownField field={fields.text} />
    </p>
  </div>
</section>

Now the markdown field switch between editing mode and normal rendering mode, depending on the layout service data that is available to it.

Conclusion

While this post covered a markdown field, there are many other types of fields that you can easily build using this technique. I will likely refactor this a bit more and perhaps eliminate the preview window and just provide a button for authors to toggle between the two different modes.

More posts soon about my journey in porting over this blog to Sitecore JSS!