Home > Net >  how can i render a component with condition in path in react router?
how can i render a component with condition in path in react router?

Time:02-21

i want to render a component with a condition in path prop in Route component. think of this: i want to say if path prop in Route component is /hello1 or /hello2 or /hello3and just if the path is one of these address render component </Hello>. something like this:

if(path === '/hello1' || path === '/hello2' || path === '/hello3') render component </Hello>

but in path prop in Route component. is there a way to do this in path prop or not? if not what is the best way to render a component with condition base on the path prop? thanks for your helps

CodePudding user response:

Maybe what you want is kind of change of params

<Route path="/hello/:helloId" element={<Hello/>} />

you can pass in every thing you wanna pass for helloId and it will render Hello component

CodePudding user response:

It can be done by creating an array of paths and mapping through them as follows:

{["hello1", "hello2", "hello3"].map((route) => (
   <Route
     key={route}
     path={route}
     element={<div>Hello component</div>}
   />
))}

Whatever path you add to the array, the same component will be rendered for those paths.

  • Related