Home > Back-end >  MUI Nav Tabs does not work with react-router
MUI Nav Tabs does not work with react-router

Time:10-31

Here are the four components:

App.js:

import React from 'react';
import { Route, Switch } from 'react-router-dom';
import About from './About';
import Home from './Home';

const App = () => {
  return <Switch>
    <Route path="/about">
      <About />
    </Route>
    <Route path="/">
      <Home />
    </Route>
  </Switch>
}

export default App;

Nav.js:

import * as React from 'react';
import {Box,Tabs,Tab} from '@material-ui/core';

function LinkTab(props) {
  return (
    <Tab
      component="a"
      onClick={(event) => {
        event.preventDefault();
      }}
      {...props}
    />
  );
}

export default function NavTabs() {
  const [value, setValue] = React.useState(0);

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

  return (
    <Box sx={{ width: '100%' }}>
      <Tabs value={value} onChange={handleChange} aria-label="nav tabs example">
        <LinkTab label="Home" href="/" />
        <LinkTab label="About" href="/about" />
      </Tabs>
    </Box>
  );
}

About.js:

import React from 'react'
import NavTabs from './Nav'

export default function About() {
    return (
        <div>
            <NavTabs/>
            About
        </div>
    )
}

Home.js:

import React from 'react'
import NavTabs from './Nav'

export default function Home() {
    return (
        <div>
            <NavTabs/>
            Home
        </div>
    )
}

In the Nav.js when I want to switch the tab then it does not switch to another tab. Also the URL link does not update. It always remains the first link.

Here I expect that when I switch the tab then it also changed the both component and address URL. How can I do that?

CodePudding user response:

The href attribute from a element makes the whole page refreshed, which defeats the purpose of react-router. In react-router, you're supposed to use the Codesandbox Demo

  • Related