I'm using create-react-app and a couple external modules, like react-markdown. How do I 'require' a dynamically generated filename? I have thousands of markdown files and I need to load them on the fly. My component works fine if I supply a static path, but doesn't work when I try to concatenate the path. I can't import statically because there are too many files.
Example:
import React, { useState, useEffect } from "react";
import ReactMarkdown from "react-markdown/with-html"
const MarkdownServer = ({myMarkdownFilename}) => {
const [markdown, setValue] = useState([]);
useEffect(() => {
async function fetchData() {
// this works...
// const p = require("../../assets/markdown/mymarkdown.md")
// this does not.
const p = require("../../assets/markdown/" + myMarkdownFilename);
const markdown = await fetch(p).then(res => res.text());
setValue(markdown);
}
fetchData();
}, []);
return (
<p>
<ReactMarkdown source={ markdown } escapeHtml={false} />
</p>
);
};
export default MarkdownServer;
Error:
Unhandled Rejection (Error): Cannot find module '../../assets/markdown/mymarkdown.md'