Get an active route with react-router in ReactJs

后端 未结 1 1129
一向
一向 2021-02-19 22:18

I am creating a project using reactjs.In my application i am getting the active route using this:

this.context.router.isActive

but getting unde

1条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 22:58

    The architecture has changed in react-router v4 and this.context.router.isActive is no longer supported.

    In react-router-v4, you could instead of creating a NavLink yourself use the exposed NavLink component.

    From the documentation:

    NavLink

    A special version of the that will add styling attributes to the rendered element when it matches the current URL.

    import { NavLink } from 'react-router-dom'
    
    About
    

    It also provides you an activeClassName prop:

    activeClassName: string

    The class to give the element when it is active. The default given class is active. This will be joined with the className prop.

    FAQs
    

    Why is this.context.router.isActive not supported:

    Here is an excerpt from a github issue

    Rendering a does not necessarily mean "only render when you match the current location". For example, it can be used inject the router variables from the context into a component as props.

    In , the is using the children prop, which means that it will call the children function whether or not the route matches. If the match is null, then we know that it did not match.

    If you would prefer not to use in this way, React Router offers an imperative approach with the matchPath function. This is what es and s use internally to match a location against a path.

    If your component is not receiving the Router props, then you could inject it using the withRouter HOC

    import { withRouter } from 'react-router';
    
    export class withRouter(MyComponent);
    

    0 讨论(0)
提交回复
热议问题