Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

242
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda