Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router possible to mount a component based on query param?

I'm using React, Redux, and [email protected]. I'm trying to figure out how to mount a top-level component when a specific query param is passed.. Is this possible?

So my existing routes look like this:

export default (
  <Route name="root" path="/" component={RootComponent}>
    <Route name="routeOne" path="a/route/:slug(/)" component={RouteOneComponent} />
    <Route name="routeTwo" path="a/route/:slug/:index" component={RouteTwoComponent} />
  </Route>
);

Now, I need to refactor routeTwo so that instead of being mounted at a/route/slug/1, it only mounts at a/route/slug?i=1.

is this possible? I can't seem to find anything about this in the docs. It seems that only actual routes can have a component, and the query is passed as a prop... But unfortunately this wont work for my use case. :( Any ideas?

like image 622
tdc Avatar asked Jun 15 '26 13:06

tdc


1 Answers

Yes you could use getComponent for this

<Route path="a/route/:slug" 
    getComponent={(nextState, cb) => {
       if (nextState.location.query[i] === '1') {
           cb(null, RouteTwoComponent);
       } else {
           cb(null, RouteOneComponent);
       }
    }} />

Although I think normally one would handle such split in the render method based on props.

like image 105
lanan Avatar answered Jun 17 '26 04:06

lanan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!