pass props with Lazy loading in react-router-dom v6

Viewed 1152

I need to pass props to the lazy components.

const A = React.lazy(() => import("./A"));

function App() {
return (
      <Suspense fallback={<GlobalLoader />}>
        <Routes>
          <Route path="/s/:name" element={<ValidateName />} />
          <Route path="/s" element={<Page fullsize={true}><A name='default'/></Page>} />
          <Route path="*" element={<Navigate replace to='/s' />} />
        </Routes>
      </Suspense>
)
}
const Validatename = () => {
    const {name} = useParams();
    let allowedValues =[{'name':a, ... },{'name':b, ... },{'name':c, ... }]
    let validValue = allowedValues.filter((i)=>i.name === name);
    let isValid = (validValue > 0);

    if(!isValid) return <Navigate replace to =='/s'>
    return <Page fullSize={true}><A name={name}/></Page>
}

Edit:

  1. Desired outcome: Lazy Loading for Component A.
  2. Component A is initialised with either 'default' value or value passed in URL i.e. 'name'
  3. Which value to pass is decided by ValidateName Component and default route /s.

Problem: How to pass prop 'name' in A so that it can be loaded lazily.

1 Answers

It is not possible in this outer context

Instead, you can use useParams() to get the path in the lazy loaded component A

if you want you can create a wrapper around A and call useParams() here like following however basically it is the same thing.

const AWrapper= () => {
  const { path } = useParams();
  if(path.id){
      return <A prop={path.id} />
  } else{
      return <A props="default" />
  }
};

PS: you should change A to AWrapper in Route too

Related