Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active December 28, 2021 10:44
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauschma/84eb2804781da9ddbe0d1cc241969f00 to your computer and use it in GitHub Desktop.
Save rauschma/84eb2804781da9ddbe0d1cc241969f00 to your computer and use it in GitHub Desktop.
/**
* A quick way of using Markdown inside JSX: via tagged templates
*
* Downsides:
* – Works completely dynamically (no static compilation)
* – Big downside: You must escape backticks.
* Potential work-around in template tag function: result.replace(/∆/ug, '`')
*
* Upsides:
* – Preserves line breaks (JSX doesn’t)
* – Dedents (esp. important for Markdown)
* – Markdown is interpreted directly (“raw”):
* a slash in the content is a Markdown slash, not a string literal slash
*/
import { compiler } from 'markdown-to-jsx';
/** Template tag function */
function md(templateStrings: TemplateStringsArray, ...substitutions: unknown[]) {
let md = templateStrings.raw[0];
for (let i=0; i<substitutions.length; i++) {
md += String(substitutions[i]) + templateStrings.raw[i+1];
}
if (md.startsWith('\n')) {
// Dedent
const lines = md.split('\n').slice(1);
if (lines.length > 0) {
const afterIndent = lines[0].search(/[^\s]/);
if (afterIndent >= 0) {
const indent = lines[0].slice(0, afterIndent);
md = lines
.map(l => l.startsWith(indent) ? l.slice(indent.length) : l)
.join('\n');
}
}
}
return compiler(md);
}
/** JSX component that uses the template tag function */
function Content() {
return <>
{md`
# Useful content
* Fee
* Fi
* Fo
* Fum
`}
</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment