skip to Main Content

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


    • create your env file and add condition of them, something like below.
    let Foo;
    if (process.env.REACT_APP_NODE_MODE === "premium-user") {
        Foo = lazy(() => import('./modules/foo.tsx'));
    }
    
    function App() {
        return (
            <>
                {process.env.REACT_APP_NODE_MODE ? <Foo /> : null}
            </>
        )
    }
    
    Login or Signup to reply.
  1. Fix that by using the lazy loaded component in a React.Suspense:

    const Foo = React.lazy(() => import('./modules/foo.tsx'));
    
    //...
    
      return (
        <div>
          ...
    
          {flag && (
            <React.Suspense>
              <Foo />
            </React.Suspense>
          )}
        </div>
      );
    

    Like that the component’s codebase will only be fetch once flag is true.

    See this example for a demo:

    Edit react-suspense demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search