'MUI Nav Tabs does not work with react-router
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, when I switch the tab then it also changed the both component and address URL. How can I do that?
Solution 1:[1]
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 Link
component and provide the to
prop to tell react-router to navigate to a different route without changing the application state:
// <a href='/about' {...} />
<Link to='/about' {...} />
You can fix it by replacing the root component of Tab
with Link
instead of a
, and change the href
to to
prop:
// <Tab component='a' label="Home" href="/" />
<Tab component={Link} label="Home" to="/" />
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | NearHuscarl |