3

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.

2
  • 1
    It's unclear what you are wanting or trying to do. Please edit your question to include a more representative code example. stackoverflow.com/help/minimal-reproducible-example Commented Feb 7, 2022 at 17:52
  • 1
    I skipped some part to ask 'to the point' question. Codes may make things more specific and sort of troubleshooting. Suggestion taken and hence edited the question for more clarity. Thanks. Commented Feb 9, 2022 at 8:34

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I simplified the question, I need to pass certain props other than 'what I am getting thro useparams'. Like, IF userparams:id is valid then element <A/>, ELSE <A prop="default"/>
I see, however it is still not possible. You have to move that logic down a bit. Instead you can create a wrapper like I mentioned in the updated answer if it helps.

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.