Home > front end >  How to make material ui tabs be active for only specific url
How to make material ui tabs be active for only specific url

Time:10-20

so I am trying to figure out how to handle a clash an issue I am seeing with having the active tab indicator on the right tab. So I have some tabs in my navbar that will take you to three different routes. However, there are two routes that are pretty similar.

<Tabs indicatorColor="primary" value={this.state.tabsValue} onChange={this.setTabsValue}>
                    <Tab className={classes.tab}
                      label="Main"
                      value="main"
                      component={Link}
                      to="/main"
                      classes={{ selected: classes.selectedTab, }} />
                    <Tab className={classes.tab}
                      label="Shoes"
                      value="shoes"
                      component={Link}
                      to="/sale/shoes"
                      classes={{ selected: classes.selectedTab, }} />
                    <Tab className={classes.tab}
                      label="Sale"
                      value="sale"
                      component={Link}
                      to="/sale"
                      classes={{ selected: classes.selectedTab }} />
                  </Tabs>

  setTabsValue = (obj, val) => {
    this.setState({
      tabsValue: val
    });
  };

So there are two routes that are pretty similar. The tab with associated route '/sale/shoes' and the tab with associated route '/sale'. I want to get it so that the 'Sale' tab should only be active for the route '/sale'. But it seems that if the user were to be on the '/sale/shoes' route, the Sale tab would be active. Im guessing because both tabs have a route that has 'sale' in it. Any way to take care of this?

CodePudding user response:

From what I can tell it seems like you may want to switch to using the NavLink component which has built-in route path matching, and then only need to specify the exact prop of the NavLink to get it to exactly match a given URL pathname.

<Tabs
  indicatorColor="primary"
  value={this.state.tabsValue}
  onChange={this.setTabsValue}
>
  <Tab
    classes={{ selected: classes.selectedTab }}
    className={classes.tab}
    label="Main"
    value="main"
    component={NavLink}
    to="/main"
    exact
  />
  <Tab
    classes={{ selected: classes.selectedTab }}
    className={classes.tab}
    label="Shoes"
    value="shoes"
    component={NavLink}
    to="/sale/shoes"
    exact
  />
  <Tab
    classes={{ selected: classes.selectedTab }}
    className={classes.tab}
    label="Sale"
    value="sale"
    component={NavLink}
    to="/sale"
    exact
  />
</Tabs>
  • Related