Search code examples
javascriptreactjsreduxreact-routerflux

Link to dynamic active class?


router for routing purpose in my react app.

Mine routing is defined in given manner:

<Route path={food/:cuisine/:pageNo} component={foodList}

and my navBar have following navigation:

<Link to={"/food/italian/1"} activeClassName="active">Italian</Link>
<Link to={"/food/indian/1"} activeClassName="active">Indian</Link>

but when visit page no. 2("/food/indian/2") of that component then myActive class of navBar is not showing. If there are any alternate method to solve this problem then it will be great.

Thanks.


PS: I don't want to put all conditions like because the app has more than 15 different cuisine

if(this.props.params.cuisine=="Indian){
    //then add .active in my Link to class
}

=======


Solution

  • just use conditional javascript for given case.

    like :

        if(this.props.params.cuisine=="Indian){
        //then add .active in my Link to class
    }
    

    it will work perfectly for you. activeClass will compare whole route path and if it's true then they will add class active.

    Alternate option: If u can create a constant value using splice function of javascript to get ur suffix of url .

    then create two variable.

    for example:

    var indianPrefix= "/food/indian/"+ urlSuffix;
    var italianPrefix= "/food/italian/"+ urlSuffix;
    

    then use:

    <Link to={italianPrefix} activeClassName="active">Italian</Link>
    <Link to={indianPrefix} activeClassName="active">Indian</Link>
    

    bug: By using this method on clicking the tab you will be landing on the same page always.

    Thanks.