Created
February 20, 2023 21:45
-
-
Save coreyward/b3bb133f501510ab14b119c0864b7ace to your computer and use it in GitHub Desktop.
Example of using React 18 Lazy to trigger code splitting when using an import map to render a Sanity-based list of components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Suspense } from "react"; | |
const componentMap = { | |
sectionOne: React.lazy(() => import("./SectionOne")), | |
sectionTwo: React.lazy(() => import("./SectionTwo")), | |
}; | |
const Section = ({ _type, ...sectionProps }) => { | |
const SectionComponent = componentMap[_type]; | |
return ( | |
<Suspense fallback={<div>Loading section…</div>}> | |
<SectionComponent {...sectionProps} /> | |
</Suspense> | |
); | |
}; | |
export default Section; | |
// Then, to render content: | |
const Content = ({ sections }) => ( | |
<div> | |
{sections.map((section) => ( | |
<Section key={section._key} {...section} /> | |
))} | |
</div> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment