4

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?

1 Answer 1

5

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="/" />

Codesandbox Demo

Sign up to request clarification or add additional context in comments.

3 Comments

It's working fine. Thanks. You use the tab component in the route. But I want to use the tab component inside the Home or Contact component. Is this possible?
@MijanurRahman do the same thing just use absolute paths in your tab component. stackoverflow.com/questions/61130162/…
Yeah, but the tab element is broken like this and doesent have the animations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.