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.
Ok, so you don't need conditional imports, you just want to do conditional rendering. That's waaaaay simpler.
Example:
import { FormA } from "./FormA";
import { FormB } from "./FormB";
const MyComponent = ({ which }) => {
return <>
{which === "form-a" && <FormA />}
{which === "form-b" && <FormB />}
<>;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.