Home > Mobile >  How can I use React lazy to Router
How can I use React lazy to Router

Time:11-29

I want to pass the props from router to component

function TestComponent({myProps: string}): {
  console.log(myProps)
  useEffect(...)
  return (
    <>...</>  
  )
};

My router use react lazy like this

import React, { lazy } from 'react';
export const routes = [
  ...
  {
    path: '/test/testComponent',
    exact: true,
    component: lazy(
      () => import('pages/test/TestComponent/index'),
    ),
  },
  ...
];

I find this way

{
  path: '/test/testComponent',
  component(): React.ReactElement {
  return <DeviceAssignmentLog myProps=''hello />;
  },
},

but I have to use lazy with that

how can I solve...

CodePudding user response:

You can just assign the lazy loaded component to a variable and then pass the required props into the config object so the inside the router file you do something like this

import React, { lazy } from 'react';

const LazyLoadedComponent = lazy(()=> import('/path-to-component'))

const routes = [
  ...
  {
    path: '/test/testComponent',
    component:()=>(<LazyLoadedComponent myProps='required-prop-value'  />),
  },
  ...
]

CodePudding user response:

import React, { Suspense, lazy } from 'react'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'

const Home = lazy(() => import('./pages/Home'))

const App = () => {
  return (
    <Router>
      <Suspense>
        <Routes>
          <Route path="/" element={<Home myProps={'hello'} />} />
          // Your routes more here
        </Routes>
      </Suspense>
    </Router>
  )
}

export default App
  • Related