I am using markdown to jsx as markdown parser. How can I give a custom id to a heading in markdown?
### Generation of keys {#custom-id} is giving:
<h3 id="generation-of-keys-custom-id">Generation of keys {#key-generation}</h3>
but I want:
<h3 id="custom-id">Generation of keys </h3>
You cannot do this with markdown-to-jsx as it currently exists. You can change the ID by writing some custom slugify function on the options argument but you won't be able to change the content within the heading.
Here is the relevant code for how it creates Heading components from JSX. Here is the Regular Expression it uses to parse out the heading:
/^ *(#{1,6}) *([^\n]+?)(?: +#*)?(?:\n *)*(?:\n|$)/
Visualized as
You can see that they capture two pieces of information:
h1 through h6)Back to the library, in the _parse function, we return an Object from our regular expression match:
_parse(capture, parse, state) {
return {
content: parseInline(parse, capture[2], state),
id: options.slugify(capture[2]),
level: capture[1].length,
}
},
You can see they create an id property using that slugify options (which has a sane default). Here is your opportunity to change how the ID is formed.
However, you can see the content doesn't have any room for customization.
The library then uses a _react function to finally transform the parsed object into a JSX node:
_react(node, output, state) {
node.tag = `h${node.level}`;
return (
<node.tag id={node.id} key={state._key}>
{output(node.content, state)}
</node.tag>
)
},
I'd look into opening a PR on the repository, which has a 3rd capturing group using some pre-defined syntax (perhaps with {#custom-id-here} as you have it). Otherwise, you can open a PR to provide another optional function that transforms the content before it is passed off to the final _react call.