Skip to content Skip to sidebar Skip to footer

React-Markdown Custom Component Declaration, How Can I Declare In The Renderer To Use A Custom Component?

Problem Using React-Markdown I can fully use my custom built components. But this is with specific pre-built keywords in the markdown. Like paragraph or images. That works PERFECTL

Solution 1:

I know its most likely a little late for your purposes, but I've managed to solve this issue using a custom remark component.

Essentially you'll need to use the remark-directive plugin as well as a small custom remark plugin (I got this plugin straight from the remark-directive docs)

Then in react markdown you can specify the plugins, custom renderers and custom tags for eg.

import React from 'react'
import ReactMarkdown from 'react-markdown'
import {render} from 'react-dom'
import directive from 'remark-directive'
import { MyCustomComponent } from './MyCustomComponent'
import { visit } from "unist-util-visit" 
import { h } from "hastscript/html.js"

// react markdown components list
const components = {
  image: () => <Footer/>,
  myTag: MyCustomComponent
}

// remark plugin to add a custom tag to the AST
function htmlDirectives() {
  return transform

  function transform(tree) {
    visit(tree, ['textDirective', 'leafDirective', 'containerDirective'], ondirective)
  }

  function ondirective(node) {
    var data = node.data || (node.data = {})
    var hast = h(node.name, node.attributes)

    data.hName = hast.tagname
    data.hProperties = hast.properties
  }
}

render(
  <ReactMarkdown components={components} remarkPlugins={[directive, htmlDirectives]}>
    Some markdown with a :myTag[custom directive]{title="My custom tag"}
  </ReactMarkdown>,
  document.body
)

So in your markdown wherever you have something like :myTag[...]{...attributes} you should render the MyCustomComponent with attributes as props.

Sorry I haven't tested the code, but hopefully it communicates the gist of things, if you need a working example let me know and I'll do my best to set one up.


Post a Comment for "React-Markdown Custom Component Declaration, How Can I Declare In The Renderer To Use A Custom Component?"