I have a folder called modules. Inside that folder there are some components. I want to conditionally load those components if their corresponding .tsx
file exist. After many days trying to figure out how to do that without Node.js and only using React and ES6 features, I found the following solution by defining some flags:
let Foo;
if (flag === true) {
Foo = lazy(() => import('./modules/foo.tsx'));
}
function App() {
return (
<>
{flag ? <Foo /> : null}
</>
)
}
Now the problem is that the flag should be fetched from an API and I don’t know how to use lazy
with fetched data that indicate which module files exist.
2
Answers
Fix that by using the lazy loaded component in a
React.Suspense
:Like that the component’s codebase will only be fetch once
flag
is true.See this example for a demo: