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?
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?
-
import()
isn't any different than any other promise in this regard. CallsetState
inthen
. Wherever possible, use synchronous import. It's unclear from the question why would it be dynamic, since import module is known. – Estus Flask Commented Sep 14, 2018 at 17:11 - assuming this is a real changelog, it isn't going to change while the app runs, because the app won't be silently live-updating itself. Parse the .md file to something JS can work with during your build step and bundle that in. – Mike 'Pomax' Kamermans Commented Sep 14, 2018 at 17:42
3 Answers
Reset to default 5Here's one way:
class MyComponent extends React.Component {
state = {html: null}
ponentDidMount() {
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 ponentDidMount
(React remends 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.
I'd use await
keyword within an async
method.
async function render() {
var markup = await import('../changelog.md');
// ...
}
import your .md file at start like this.
import yourMDObject from '../changelog.md';
and then you can use fetch()
like this
fetch(yourMDObject).then(obj =>obj.text()).then(..)