简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM