Jordan
Jordan

Reputation: 2523

Component connected to withRouter not receiving correct match properties

I'm having some trouble getting the correct match properties to show in my component connected to withRouter

My router map looks like this

<BrowserRouter>
  <div>
    <Switch>
      <Route path="/" component={HomePage} />
      <Route path="/start/:short_code/*" render={() => <div>Magic</div>} />
      <Route path="/events" component={EventsPage} exact/>
      <Route path="/events/:auction_code" />
      <Route component={NotFoundPage} />
    </Switch>
    <MainMenu />
    <LoginPage />
    <HoldersDrawer />
  </div>
</BrowserRouter>

In my HomePage component I have it wrapped in both withRouter and redux

export default withRouter(connect(mapStateToProps)(HomePage));

However, anywhere I attempt to access this.props.match I am only seeing

{
    isExact:false,
    params:{},
    path:"/",
    url:"/"
}

Even if I have set my URL to one of the routes I've outlined

The home page has a QR scanner on it and I want that active no matter which route the user is on, but I also want to be able to access the current route the user is on, on the HomePage For instance, the user can navigate to events/auction_code and when they perform and action I need to be able to pass the relevant auction_code to the API call said action calls, currently I have to parse that out of the current location pathname data. It would be nice if I could just get it from the match.params object.

Can someone see something I may be doing wrong here that would cause this issue?

Upvotes: 1

Views: 388

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282160

The reason that withRouter doesn't provide you the match props of the matched Route is because withRouter gives you access to the history object’s properties and the closest <Route>'s match and in your case the HomePage doesn't have any closest matched Route.

You could achieve what you need by passing on the handler to the Routed component and lifting the action up to the Component that renders the Route. Something like

<BrowserRouter>
  <App/>
</BrowserRouter>

and defining App to have handlers like

class App extends React.Component {
    handlerFunction = (match) => {
       //your action based on match here
    }

    render() {
       return (
         <div>
            <Switch>
              <Route path="/" component={HomePage} />
              <Route path="/start/:short_code/*" render={() => <div>Magic</div>} />
              <Route path="/events" render={(props) => <EventsPage handler={this.handlerFunction} {...props}/>} exact/>
              <Route path="/events/:auction_code" />
              <Route component={NotFoundPage} />
            </Switch>
            <MainMenu />
            <LoginPage />
            <HoldersDrawer />
        </div>
       )
    }
}

Upvotes: 1

Related Questions