Search code examples
reactjsreact-router-dom

How to fix React Router component not updating as route changes


I am using react-router-dom for routing in my reactJs application. I have a Route, Account, that has nested routes in it. In the Account component I want to display different components based on the current route (param.id). Right now the initial component is rendering, but when I click on a link my Account component still renders that initial component regardless of that change in url. How can I get my Account component to update on the change of url. Or should I be doing something in the AccountSwitch component to recognize the change of url and update it's current value for props.match.params.id ?

// app.js
<Router>
    <Route path="/account" component={Account} />
</Router>

// account.js
class Account extends Component {
    render() {
        return (
            <div>
                <Link to="/account">Messages</Link>
                <Link to="/account/orders">Orders</Link>

                <Route exact path="/account" component={Messages} />
                <Route path="/account/:id" component={AccountSwitch} />
            </div>
        )
    }
}

// accountSwitch.js
const AccountSwitch = props => {
    switch(props.match.params.id) {
        case '':
            return (
                <AccountMessages />
            );
        case 'orders':
            return (
                <AccountOrders />
            )
        default:
            return <span>select a page<span/>
    }
}

Solution

  • In https://github.com/Rynebenson/og-website/blob/master/src/_components/wrappers/Account/index.js where you are using the route switch please try to use exact match for "/account" and see if that works.

    Use:

    <Switch>
      <Route exact path={`/account`} component={AccountMessages} />
      <Route path={`/account/:id`} component={AccountSwitch} />
    </Switch>

    All while exporting try this:

    export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Account))