I got a problem and can’t find the solution. Sorry if it’s a dumb one but I’m a newby with React.
I want to dynamically load a component inside useEffect hook. I can load the file but cant access the function.
Here is my main file
footer.js
import React, { useEffect, useState} from "react";
const MyMainComponent = ({ type }) => {
const [preFooter,setPreFooter ] = useState(null)
useEffect(() => {
if (type === "page") {
import( "./prefooter/preFooterPage")
.then(PreFooterPage =>
setPreFooter(result)
);
} else {
import( "./prefooter/preFooterArticle")
.then(x =>
setPreFooter(result)
);
}
}, [type]);
return (
//I want to use the result like this : <preFooter/>
...
)
}
export default MyMainComponent
Here are the two different components :
preFooterArticle.js
import React from "react";
const PreFooterArticle = () => {
return (
<h2>Hi, I'm a pre Footer for blog posts !</h2>
)
}
export default PreFooterArticle
preFooterPage.js
import React from "react";
const PreFooterPage = () => {
return (
<h2>Hi, I'm a pre Footer for pages !</h2>
)
}
export default PreFooterPages
The import and set state work fine but I dont know how return the state as a component ?
Thanks a lot for your help
2
Answers
If you want to return a state as a component use redux.
https://redux.js.org/tutorials/essentials/part-1-overview-concepts
As example, the index.js should look like this:`import React from
The rerenderEntireTree function helps to rerender as the state changes as well as subscribe
and create reducer files as for example this:
Before the dynamic import is loaded, you need to supply a default component state (
() => null
), sinceuseState
treats any functions passed in init as initializer, you’ll need to wrap it in another function (() => () => null
).When you import a file, you get an object, with the actual imports as properties of the object, so you need to extract your component (
{ default: comp }
). Then you set it on your state, and again need to wrap it with a function, so it won’t be treated as an updater function –setPreFooter(() => comp)
.Code (Sandbox):
However, instead of inventing the wheel, you can use React.lazy to load the component dynamically, and wrap it with to provide a fallback until the component is loaded.
Code (sandbox):