Create a loop to import files dynamically in React

Viewed 8393

Consider I have a folder with .md files like this:

/static/blog/
  example_title.md
  another_example.md
  three_examples.md

and I have an array including all titles:

const blogEntries = ["example_title", "another_example", "three_examples"]

in my component I want to import all of them, notice that there could be fewer or more.

Is there any way to dynamically import them similar to:

for (let entry in blogEntries) {
  import `Markdown_${entry}` from `/static/blog/${entry}.md`
}

and later in my render I can do:

<Markdown_three_examples />

the above obviously would not work, but I'm looking for a way to achieve similar.

3 Answers

You can try to use dynamic imports - import(). As the name implies, they work during runtime, and can have dynamic urls.

Note: currently they are supported natively by Chrome and Safari, but not by firefox, IE, and Edge. However, you can use webpack to solve that.

const blogEntries = ["example_title", "another_example", "three_examples"]

const loadEntries = (entries) =>
  Promise.all(entries.map((entry) => import(`/static/blog/${entry}.md`)));

loadEntries(blogEntries)
  .then((entries) => console.log(entries));
const Markdown = {}

for (let entry in blogEntries) {
  Markdown[entry] = require(`/static/blog/${entry}.md`)
}
Related