Home > other >  How to use react router with MUI tabs
How to use react router with MUI tabs

Time:12-17

Can you please explain how I make my routes work with MUI tabs? Since I don't write my code like this and do not use MUI very often, I don't understand how to make it work. any ideas please?

  • I removed the imports to focus on the main problem and make the code shorter.

This is my NavBar.js Component:

  const NavBar = props => {
  const [value, setValue] = useState(0);

  const handleChange = (_e, newValue) => {
    setValue(newValue);
  };

  return (
    <AppBar position="static" color="transparent" style={{ position: "fixed", top: 0 }}>
      <Tabs
        value={value}
        onChange={handleChange}
        aria-label="Navigation"
        indicatorColor="primary"
        textColor="primary"
      >
        <Tab label="Home" index={0} />
        <Tab label="Favorites" index={1} />
      </Tabs>
    </AppBar>
  );
};

And my AppRouter.js Component

const AppRouter = () => {
  return (
    <ThemeProvider>
      <Router>
        <NavBar />
        <Switch>
          <Route exact path="/" component={Home} />
        </Switch>
      </Router>
    </ThemeProvider>
  );
};

CodePudding user response:

Did you try to add in handleChange hard coded routing, like history.push based on value? Not sure is it what you want.

CodePudding user response:

Ok so I found the solution. In my AppRouter.js I got this:

import React from "react";
import { HashRouter as Router, Switch, Route } from "react-router-dom";
import { Home, Favorites } from "pages";
import { ThemeProvider } from "theme";
import NavBar from "components/NavBar";

const AppRouter = () => {
  return (
    <ThemeProvider>
      <Router>
        <NavBar />
        <Switch>
          <Route exact path="/favorites" component={Favorites} />
          <Route exact path="/" component={Home} />
        </Switch>
      </Router>
    </ThemeProvider>
  );
};

export default AppRouter;

and in my NavBar.js I added this and it allows me to switch between them:

import React, { useState } from "react";
import { AppBar, Tabs, Tab } from "@material-ui/core";
import { Home, Favorites } from "pages";
import { Route, BrowserRouter, Switch, Link } from "react-router-dom";

const NavBar = props => {
  const [value, setValue] = useState(0);

  const handleChange = (_e, newValue) => {
    setValue(newValue);
  };


  return (
    <AppBar position="static" color="transparent" style={{ position: "fixed", top: 0 }}>
      <Tabs
        value={value}
        onChange={handleChange}
        aria-label="Navigation"
        indicatorColor="primary"
        textColor="primary"
      >
        <Tab label="Home" index={0} component={Link} to={"/"} />
        <Tab label="Favorites" index={1} component={Link} to={"/favorites"} />
      </Tabs>
    </AppBar>
  );
};

export default NavBar;

the problem I face now is that for some reason I lose my local storage and I change my route

  • Related