Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic import() file in JS

I need to import markup file dynamically slice part of file and add result to variable and render result in my React app:

import('../changelog.md').then(...) 

I trying to do it in render() method with all logic but I have problems. Where I need to import it (in class or outside) and how to get value of promise to paste it to variable?


1 Answers

Here's one way:

class MyComponent extends React.Component {

    state = {html: null}

    componentDidMount() {
        import('../changelog.md').then(mod => {
            this.setState({html: mod.default})
        })
    }

    render() {
        return this.state.html ? <div dangerouslySetInnerHTML={{__html:this.state.html}} /> : <p>Loading...</p>
    }
}

Assuming you have a .md loader and it returns HTML.

import() returns a Promise. So you'll have to wait for it to resolve before you can render it. Easiest way to do that is to do it in componentDidMount (React recommends you put all ajax request there and this is kind of similar) and then copy it into state to force a re-render when it's done.

like image 138
mpen Avatar answered Sep 15 '25 07:09

mpen