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/>
}
}
To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console.
To solve the error "export 'Redirect' (imported as 'Redirect') was not found in 'react-router-dom'", use the Navigate component instead of Redirect , e.g. <Navigate to="/dashboard" replace={true} /> . The Navigate component changes the current location when it's rendered.
The primary difference between them lies in their usage. React Router DOM is for web applications and React Router Native is for mobile applications made with React Native.
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))
Have you tried withRouter?
import { withRouter } from 'react-router-dom'
const AccountSwitch = props => {
switch(props.match.params.id) {
case '':
return (
<AccountMessages />
);
case 'orders':
return (
<AccountOrders />
)
default:
return <span>select a page<span/>
}
}
export default withRouter(AccountSwitch)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With