Search code examples
reactjsmaterial-uireact-router-v4

Material-UI's Tabs integration with react router 4?


The new react-router syntax uses the Link component to move around the routes. But how could this be integrated with material-ui?

In my case, I'm using tabs as the main navigation system, So in theory I should have something like this:

const TabLink = ({ onClick, href, isActive, label }) => 
  <Tab
    label={label}
    onActive={onClick}
  />



export default class NavBar extends React.Component {
  render () {
    return (
      <Tabs>
        <Link to="/">{params => <TabLink label="Home" {...params}/>}</Link>
        <Link to="/shop">{params => <TabLink label="shop" {...params}/>}</Link>
        <Link to="/gallery">{params => <TabLink label="gallery" {...params}/>}</Link>
      </Tabs>
    )
  }
}

But when it renders, material-ui throws an error that the child of Tabs must be a Tab component. What could be the way to proceed? How do I manage the isActive prop for the tab?

Thanks in advance


Solution

  • My instructor helped me with using React Router 4.0's withRouter to wrap the Tabs component to enable history methods like so:

    import React, {Component} from "react";
    import {Tabs, Tab} from 'material-ui';
    import { withRouter } from "react-router-dom";
    
    import Home from "./Home";
    import Portfolio from "./Portfolio";
    
    class NavTabs extends Component {
    
     handleCallToRouter = (value) => {
       this.props.history.push(value);
     }
    
      render () {
         return (
          <Tabs
            value={this.props.history.location.pathname}
            onChange={this.handleCallToRouter}
            >
            <Tab
              label="Home"
              value="/"
            >
            <div>
               <Home />
            </div>
            </Tab>
            <Tab
              label="Portfolio"
              value="/portfolio"
                >
              <div>
                <Portfolio />
              </div>
            </Tab>
          </Tabs>           
        )
      }
    }
    
    export default withRouter(NavTabs)  
    

    Simply add BrowserRouter to index.js and you're good to go.