Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
How to dynamically import a MDX Component in React?

I created an Article component which gets its title through the route parameters like this:

const Article = () => {
  const params = useParams()
  const dashedTitle = params.title.replace(/ /g, '-')
  
  return (
    <article>
      <MyMDX />
    </article>
  );
}

I want to return a MDX file with the same name as the provided title. Simply returning the <MyMDX /> component works fine if I manually import it at the top of the article with import MyMDX from '../markdowns/mymdx.mdx. However, I don't see a way to import this file dynamically, depending on the tile.

Is there a way to do this or could I do this in a better way?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I managed to find a solution to this:

const Article = () => {
    
    const params = useParams()
    const [article, setArticle] = useState()

    dashedTitle = params.title.replace(/ /g, '-')

    useEffect(() => {
        import(`../markdowns/${dashedTitle}.mdx`).then(module => {
            setArticle(module.default)
        }).catch(err => {
            console.log(err)
            setArticle(undefined)
        })
    }, [dashedTitle])

    return (
        <article>
            {article ? article : <NotFound />}
        </article>
    );
}

With useEffect, import the MDX module and then set my article variable to the module's default export (which is exactly the generated JSX component). Thus, I can use it in the return segment in case it's not undefined.

Additionally, I found a similar answer that could help.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!