Import dynamically using React

Let's assume that you want to import .md files into a React component. If the name of the file to import depends on the current URL, you'll need to import the files dynamically.

Example:

jsx
import React, { useEffect, useState } from 'react';

const App = () => {
    
    const [content, setContent] = useState(null);
    
    useEffect(() => {
        
        const importDynamically = async () => {
            
            // Getting the last part of the URL
            let url = window.location.pathname.pop();
            
            // Importing the file dynamically
            let file = await import (`../Files/${url}.md`);
            
            // Fetching the file
            let response = await fetch(file.default);
            
            // Getting the plain text
            let text = response.text();
            
            setContent(text);
            
        }
        
        importDynamically();
        
    }, []);
    
    return(
        <div>{content}</div>
    );
    
}

export default App;

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.