Created
May 28, 2020 17:43
-
-
Save jordanell/2d51f72b25586940bbf6c227cc54c44c to your computer and use it in GitHub Desktop.
Markdown to React page layout - Demos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import PropTypes from "prop-types"; | |
import React from "react"; | |
import MarkdownElement from "MarkdownElement"; | |
class MarkdownPage extends React.Component { | |
static propTypes = { | |
path: PropTypes.string.isRequired, | |
req: PropTypes.func.isRequired, | |
reqSource: PropTypes.func | |
}; | |
getSections(markdown) { | |
return markdown | |
.filter(section => !/^\s*$/.test(section)); // Remove empty lines | |
} | |
render() { | |
const { path, req, reqSource } = this.props; | |
const demos = {}; | |
let markdown; | |
// Parse markdown and JSX files | |
req.keys().forEach(filename => { | |
if (filename.indexOf(".md") !== -1) { | |
markdown = req(filename).default; | |
} else if (filename.indexOf(".jsx") !== -1) { | |
const demoName = `${path}/${filename | |
.replace(/\.\//g, "") | |
.replace(/\.jsx/g, ".js")}`; | |
demos[demoName] = { | |
name: demoName, | |
jsx: req(filename).default, | |
rawJS: reqSource(filename).default | |
}; | |
} | |
}); | |
const sections = getSections(markdown); | |
return ( | |
<div> | |
<div className="content"> | |
{sections.map((section, index) => { | |
if (/^"demo": "(.*)"/.test(section)) { | |
let options; | |
try { | |
options = JSON.parse(`{${section}}`); | |
} catch (err) { | |
console.error(err); | |
return null; | |
} | |
const name = options.demo; | |
return ( | |
<Demo key={index} demo={demos[name]} /> | |
); | |
} | |
return <MarkdownElement key={index} text={section} />; | |
})} | |
</div> | |
</div> | |
); | |
} | |
} | |
export default MarkdownPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment