How do you get Material-UI Tabs to work with react-router?

12,527

Solution 1

The way you are using Routes here are inefficient.

It should be Tabs are implemented in one place and only one place as this (simply no need to use HomeHeader in every page):

 <BrowserRouter>
    <div className={classes.root}>
      <AppBar position="static" color="default">
        <Tabs
          value={this.state.value}
          onChange={this.handleChange}
          indicatorColor="primary"
          textColor="primary"
          fullWidth
        >
          <Tab label="Item One" component={Link} to="/one" />
          <Tab label="Item Two" component={Link} to="/two" />
        </Tabs>
      </AppBar>

      <Switch>
        <Route path="/one" component={PageShell(ItemOne)} />
        <Route path="/two" component={PageShell(ItemTwo)} />
      </Switch>
    </div>
  </BrowserRouter>

as you can see tabs are asking for link and routes in the switch render compnents

for the animation I used this article: https://blog.logrocket.com/routes-animation-transitions-in-react-router-v4-9f4788deb964

here they are using react-addons-css-transition-group

please find the animation index.css file in demo

I wrapped pages from a HOC to make routing easier ( PageShell componet)

here is a working example:https://codesandbox.io/s/04p1v46qww

hope this will give you a head start

Solution 2

To track active tab you can use location as tab value. And use router location as value for Tabs component. This way you achive change tabs animation out of box and highlight active tab when load page directly.

export const Module: React.FC<IModuleProps> = props => {
    const match = useRouteMatch();
    const location = useLocation();

    return (
        <>
            <Tabs value={location.pathname} >
                <Tab label="Dashboard" component={Link} to={`${match.url}/dashboard`} value={`${match.url}/dashboard`} />
                <Tab label="Audit Results" component={Link} to={`${match.url}/audit-results`} value={`${match.url}/audit-results`} />
            </Tabs>
            <Switch>
                <Route path={`${match.url}/dashboard`}>
                    <Dashboard />
                </Route>
                <Route path={`${match.url}/audit-results`}>
                    <AuditResults />
                </Route>
                <Route path={`${match.url}`}>
                    <Dashboard />
                </Route>
            </Switch>
        </>
    );
}

Solution 3

As for the current structure above you can see that the "tabs" are getting re-rendered with the change of the routes.

The way react is built by components holding components, so if you change one component, all of its children will get rendered.

So in your case, this is how the components are structures:

MainApp >
          Route('monitor') > MonitorProductPage > HomeHeader
          Route('sensor') > SensorProductPage > HomeHeader

You can see in this example, as you change a route you change all the content and need to re-render a NEW HomeHeader.

The way, I'll structure it for making sure HomeHeader will get created once and only props will change. (both for performance and for the issue here) Is like this:

MainApp >
          Route('innerpage/*') > InnerPage > 

               > MonitorProductPage
               > SensorProductPage

like this code in react router dom https://reacttraining.com/react-router/web/example/route-config

That means you have a single route that will catch those inner pages, it could be like the above, or catch all (*) Then you will have another router inside InnerPage that will decide which page to show.

const routes = [
{
    path: "/innerpage",
    component: InnerPage
  },
  {
    path: "/monitor",
    component: MonitorProductPage,
  },
  {
    path: "/sensor",
    component: SensorProductPage
  }
];

and Component "InnerPage" will render HomeHeader and inside it will have the router that will decide of its "body"

Share:
12,527
Colin Sygiel
Author by

Colin Sygiel

Updated on June 19, 2022

Comments

  • Colin Sygiel
    Colin Sygiel about 2 years

    I am trying to get Material-UI tabs to work with routing, and while the routing is working and displaying the selected tab, the smooth animation of navigating between tabs is no longer working. How can I use react router with Material-UI tabs to keep the tab animations working as they should?

    As of now, I have the tabs in my HomeHeader.js and I am using this component to pass down the vale as props in order to change the value and thus change the selected tab.

    For simplicity, I simplified my code to show the tabs I want to be linked.

    Here is my code:

    Header.js (Component with Tabs):

    import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    import { Link } from 'react-router-dom'
    
    class HomeHeader extends Component {
    
      state = {
        value: false
      };
    
      handleChange = (event, value) => {
        this.setState({ value })
      };
    
      render() {
        const { classes, value } = this.props
    
        return (
            <AppBar className={classes.appBar} elevation={this.props.elevation}>
              <Hidden smDown>
                <Grid container justify="space-between" alignItems="center">
                  <Tabs value={value} onChange={this.handleChange}>
                    <Tab label="monitor" component={Link} to="/monitor" />
                    <Tab label="sensor" component={Link} to="/sensor" />
                  </Tabs>
                </Grid>
              </Hidden>
            </AppBar>
        )
      }
    }
    
    export default withStyles(styles)(HomeHeader)
    

    Tab 1 Component (pass value into HomeHeader.js as props):

    import React from 'react'
    
    import HomeHeader from '../components/HomeHeader'
    
    class SensorProductPage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
    
      render() {
        return (
          <div>
            <HomeHeader value={1} />
            <div> Hello </div>
          </div>
        );
      }
    }
    
    export default SensorProductPage
    

    Tab 2 Component (pass value into HomeHeader.js as props):

    import React from 'react'
    
    import HomeHeader from '../components/HomeHeader'
    
    class MonitorProductPage extends React.PureComponent {
    
      render() {
        return (
          <div>
            <HomeHeader value={0} />
            <div> Hello </div>
          </div>
        );
      }
    }
    
    export default MonitorProductPage
    
  • user8808265
    user8808265 over 5 years
    This isn't perfect unfortunately. If you load /two directly though the address bar without clicking on a tab, Item One is the tab highlighted, but it's the second tab that is actually displayed. This is quite challenging to solve actually.
  • xtrinch
    xtrinch over 4 years
    @user8808265 agreed, it's challenging. anyone got a solution?
  • Sau001
    Sau001 over 3 years
    @Nadun, The sandbox code does not meet the requirements. If you load page 2, then the Tab for page 1 is shown as active.