next.js: withRouter not getting current pathname
[ BUG ] withRouter not getting current pathname
Since version 6.1 router.pathname gets only the first loaded pathname.
To Reproduce
import Router, { withRouter } from 'next/router'
...
const ActiveLink = (props) => {
const active = (props.router.pathname === active_url) ? ' active' : ''
const onClickHandler = (e) => {
...
}
return (
<a href={props.href} className={'nav-link'+active} onClick={onClickHandler}>
{props.children}
</a>
)
}
export default withRouter(ActiveLink)
Expected behavior
When the component re-render, it should give the current pathname.
System information
- Version of Next.js: [e.g. 6.1.1]
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 4
- Comments: 16 (5 by maintainers)
Solution
connectmakes its wrapped componentpure, preventingwithRouter, placed no matter how deep in the component’s tree, from getting context updates. So in order to make your ActiveLink work, pass{pure: false}as a fourth argument to yourconnectfunction like this:I was about to open a similar issue, but while creating a reproducible example I figured out, I had code like this:
Which, as far as I understand, resulted in
contextTypesrequired bywithRouterbeing replaced with ones required byconnectfromreact-redux. If you swap the order ofconnectandwithRouterlike this:withRouter(connect()(...))you get the same faulty behaviour.Might consider this to be a bug in both
next.jsandreact-reduxas both HOC’s are not nice enough to combinecontextPropswith their first-order component arguments. New react context API could have helped here too.Workaround: don’t compose
connectandwithRouterdirectly:Screencast from a running demo https://github.com/futpib/next.js-withRouter-issue-demo:
EDIT: I think I’m still missing something, as applying the workaround above with
connectandwithRouterswapped does not work, for why that may be I don’t have a clue.@timneutkens Can this be reopened now as I provided a reproducible example above?
@timneutkens please re-open.
I believe this is a pretty big error since an example use case does not work as documented
I’m going to close this issue as there’s no reproduction.
I don’t understand why you’d ask to re-open a closed issue from mid 2018 (1,5 years old by now).
It’s generally better to create a new issue:
It’s unlikely your issue is the same as a 1,5 year old issue that didn’t have a reproduction provided.
Posting “any news” on a GitHub issue won’t get your issue solved, always provide a full reproduction that is clear and concise. If not you can use GitHub emoji reactions on the initial issue.
@srosset81 I don’t think there will be any noticeable performance issues, because rendering a “link” component is usually a very cheap operation due to its small child components subtree