skip to Main Content

I have a component library with multiple icon components that I am wanting to bring into my new project but I am wanting to lazily load, but I’m not 100% sure on how to go about this.

The icon components are all default exports from their respective component files.

I have seen the standard way of lazy loading a component:

const OtherComponent = React.lazy(() => import('./OtherComponent'));

however, the examples I see like this are simply from within the same project… Nothing seems to show from an external lib as I am wanting to do.

My component lib has a structure like:

.
└── My-Library/
    └── src/
        └── icons/
            └── svg/
                ├── person.ts
                ├── car.ts
                └── ...

with each icon component having a structure like:

export default Person = () => (
    <svg>
        ...
    </svg>
)

Is it possible to import these?

2

Answers


  1. You can lazily load these components into your main project like this:

    import React, { lazy, Suspense } from 'react';
    
    // Lazy load the icon components
    const LazyPersonIcon = lazy(() => import('My-Library/icons/svg/person'));
    const LazyCarIcon = lazy(() => import('My-Library/icons/svg/car'));
    // ...
    
    function App() {
        return (
            <div>
                <Suspense fallback={<div>Loading...</div>}>
                    {/* Use the lazily loaded icon components */}
                    <LazyPersonIcon />
                    <LazyCarIcon />
                    {/* ... */}
                </Suspense>
            </div>
        );
    }
    
    export default App;
    
    Login or Signup to reply.
  2. ince you mentioned that you are able to import components like import { component } from 'My-Library', I assume your library is exporting components in a way that’s compatible with direct imports.

    Here’s how you might do it:

    import React from 'react';
    import { PersonIcon, CarIcon } from 'My-Library'; // Adjust the actual imports
    
    function App() {
        return (
            <div>
                {/* Use the icon components */}
                <PersonIcon />
                <CarIcon />
            </div>
        );
    }
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search