score:-1

Just set value to your tab, that should do the work

<Tab value={0} label="Item One" />
<Tab value={1} label="Item Two" />
<Tab value={2} label="Item Three" />

score:0

This simple solution worked for me. grabing url from the browser using window.location.pathname and updating value state whenever browser is refreshed and reloaded using componentDidmount lifecycle method.

    class SimpleTabs extends React.Component {
      state = {
        value: 0,
      }
    
      handleChange = (event, `enter code here`value) => {
        this.setState({ value })
      }

     componentDidMount() {
     // assuming Item one as url "/" Item two as url "/itemTwo" and so on
      switch (window.location.pathname) {
      case "/":
        this.setState({ value:0 })
        break;
      case "/itemTwo":
       this.setState({ value:1 })
        break;
      case "/itemThree":
        this.setState({ value:2 })
        break;
   
      default:
        this.setState({ value })
        break;
     }
    }
    
      render() {
        const { classes } = this.props
        const { value } = this.state
    
        return (
          <div className={classes.root}>
            <AppBar position="static">
              <Tabs value={value} onChange={this.handleChange}>
                <Tab label="Item One" />
                <Tab label="Item Two" />
                <Tab label="Item Three" />
              </Tabs>
            </AppBar>
            {value === 0 && <TabContainer>Item One</TabContainer>}
            {value === 1 && <TabContainer>Item Two</TabContainer>}
            {value === 2 && <TabContainer>Item Three</TabContainer>}
          </div>
        )
      }
    }

score:1

I manage to solve this by using the useLocation hook and returning the state value based on the path.

const currentTab = () => {
    let path = location.pathname;
    if (path === "/") return 0;
    else if (path === "/path2") return 1;
    else if (path === "/path3") return 2;
    else if (path === "/path4") return 3;
    else if (path === "/path5") return 4;
};  

and then replacing the useState value from 0 (the first tab) to the currentTab function.

const [value, setValue] = useState(currentTab);

This solution helped me a lot, saw it somewhere else, so I hope it helps anyone!

score:3

That is because on page refresh the component is reinitialized, the state.value is set to 0.

The onChange method needs to store the selected tab somewhere, in the page URL for example.

In the component constructor or on componentDidMount the state.value needs to be set from the storage where it was set previously.


Related Query

More Query from same tag