Skip to content

Instantly share code, notes, and snippets.

@Xiphe
Created January 16, 2017 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xiphe/7e6915a458fbf880b6501bcb5b6b8fdc to your computer and use it in GitHub Desktop.
Save Xiphe/7e6915a458fbf880b6501bcb5b6b8fdc to your computer and use it in GitHub Desktop.
seamlessly embedded JSX in markdown files on the fly #hipsterstuff
'use strict';
const md = require('markdown-it')();
const mdJsxPlugin = require('markdown-it-jsx');
const reactJsx = require('react-jsx');
const React = require('react');
const reactDom = require('react-dom/server');
const originalCreateElement = React.createElement;
md.use(mdJsxPlugin);
const jsxString = md.render(`
## Test
<Hello postfix={'!'}>World</Hello>
<p>How are you{getQuestionMark()}</p>
<Hello postfix='?'><Hello postfix="??" />
<Hello postfix="???">Universe</Hello>
</Hello>
<div class="lorem">ipsum</div>
<span class='dolor'>sit</span>
<div className="this-is-a-table">
\`\`\`markdown
Funky | Table
------|------
a | b
\`\`\`
</div>
`);
const Hello = (props) => {
return originalCreateElement('span', null, [
'Hello ',
props.children,
props.postfix,
]);
};
const getQuestionMark = () => '?';
const BetterH2 = (props) => {
return originalCreateElement('h1', props);
};
function replaceType(type) {
if (type === 'h2') {
return BetterH2;
}
return type;
}
const ProxyReact = {
createElement(someType) {
const newArgs = [].slice.call(arguments);
newArgs.splice(0, 1, replaceType(someType));
return originalCreateElement.apply(ProxyReact, newArgs);
},
};
const parsedJsx = reactJsx.server(`<div>${jsxString}</div>`)({ React: ProxyReact, Hello, getQuestionMark });
console.log(reactDom.renderToStaticMarkup(parsedJsx));
/*
<div>
<h1>Test</h1>
<span>Hello World!</span>
<p>How are you?</p>
<span>
Hello <span>Hello ??</span>
<span>Hello Universe???</span>?
</span>
<pre><code>&amp;lt;div class=&amp;quot;lorem&amp;quot;&amp;gt;ipsum&amp;lt;/div&amp;gt;
&amp;lt;span class=&#x27;dolor&#x27;&amp;gt;sit&amp;lt;/span&amp;gt;
</code></pre>
<div class="this-is-a-table"><pre><code class="language-markdown">Funky | Table
------|------
a | b
</code></pre>
</div>
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment