I want to render different Components based on some checkboxes selection pattern without having to import components that may not be used.
I have an Array which contains the Component names (I used numbers as an example) and I want to import each component based on the values of the array.
I came up with something like this:
import {Suspense} from 'react'
export default function CreationForm() {
const docs = [1,3,5]
return (
<Suspense fallback={<div>Loading...</div>}>
{
docs.map(val => React.lazy(() => import(`documents/${val}.jsx`)))
}
</Suspense>
)
}
I know this solution does not work but I think it explains what I am trying to do.
I could try using state but the actual "docs array" is an state variable in the real application so it could cause duplicated state.
I did this as a test and worked:
const A = React.lazy(() => import(`documents/1.jsx`))
...
*** SNIP ***
...
<Suspense fallback={<div>Loading...</div>}>
{
docs.map((val) => <A/>)
}
</Suspense>
But I cannot dynamically import each component like this.
importdoes. Typically your IDE will help in managing your imports. You also don't typically import conditionally (or at all). You might render conditionally, but the imports are static.