1

I would like to know if it's possible to lazy load a component in a generic way (in a function for example).

Example:

function renderLazyComponent() {
  if (/* condition */) {
    return React.lazy(async () => {
      const module = await import('mathLibraryForExample');
      return { default: (props) => <p>{module.multiply(1, 2)}</p> }
    })
  } else {
    return React.lazy(async () => {
      const module = await import('mathLibraryForExample');
      return { default: (props) => <p>{module.division(1, 3)}</p> }
    })
  }*/
}


function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      { renderLazyComponent() } 
    </Suspense>
  );
}
Because I always get this error: ```Objects are not valid as a React child (found: object with keys {$$typeof, _ctor, _status, _result}). If you meant to render a collection of children, use an array instead.```

1 Answer 1

1

I suppose path './components/' is location of your components.

First approach:

const FirstComponent = lazy(() => import('./components/first'));
const SecondComponent = lazy(() => import('./components/second'));
function App() {
  return (
    <>
      <Suspense fallback={<div>Loading</div>}>
        { condition ? <FirstComponent /> : <SecondComponent /> }
      </Suspense>
    </>
  );
}

Second approach:

function renderLazyComponent(component) {
   return lazy(() => import('./components/' + component));
}
function App() {
  return (
    <>
      <Suspense fallback={<div>Loading</div>}>
        { renderLazyComponent('first') } 
        { renderLazyComponent('second') } 
      </Suspense>
    </>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

This gives an error that an object cannot be rendered in React when I tried it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.