kimiro
kimiro

Reputation: 305

React Routing : How can I be redirected to matching tab according to url?

I have been stuck for several days for this problem. My problem is how to jump to purposing tab when I enter url of that tab.

You can find my code here

In this code I made a tab using material-ui tabs component. And as you can see from the working example in codesandbox, I attached tab suburls after the page url with the delimiter #.

This is done by handleChange method.

import { useHistory, useLocation } from "react-router-dom";
const location = useLocation();

const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
  setValue(newValue);
  history.replace({
    hash: `${tabs[newValue].suburl}`
  });
};

And handleChange method is called on Tabs component onChange props. Like this:

<Tabs
  value={value}
  onChange={handleChange}
  aria-label="Top Statistic Tabs"
>
  {TabHeaders}
</Tabs>

You can see url changes when toggling different tabs in working example.

However, my problem is the reverse is not working. When you enter a tab url and press enter, it does not jump to matching tab. I think this is because matching router is not defined to each urls but not be sure and don't know how to do it.

The skeleton code is from https://material-ui.com/components/tabs/#customized-tabs and I just added suburl adding part.

Please help me by answering anything you know.

  1. React version : 17.0.2
  2. React-router-dom version : 4.3.4
  3. Material-ui version: 4.12.3

Thanks in advance.

Upvotes: 0

Views: 2010

Answers (1)

Junaid Faryad
Junaid Faryad

Reputation: 1707

Your codesandbox is updated. Please review it.

Active tab is being controlled by the index and it worked fine, when you manually click on the tab and updating the index. The problem on refreshing the page is due to this below code in initialization.

const [value, setValue] = React.useState(0);

On initialization, you're always setting the first tab as active tab instead of taking the location hash into account. To solve this issue, one of the solution is you can use a ternary check to see if there is some hash in the location object and initialize the value state based on that.

const [value, setValue] = React.useState(
location?.hash === "#tokentxnsErc20"
  ? 2
  : location?.hash === "#internaltx"
  ? 1
  : 0
);

Upvotes: 1

Related Questions