Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda