Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs keep Material Ui Tab selected on refresh

Hi I'm using React Material UI Tab and I noticed that on refresh the website doesn't keep the tab selected. How can I prevent this from happening? This is a code-type of material ui tab

class SimpleTabs extends React.Component {
  state = {
    value: 0,
  }

  handleChange = (event, value) => {
    this.setState({ value })
  }

  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>
    )
  }
}
like image 408
AC1 Avatar asked Oct 16 '22 07:10

AC1


1 Answers

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.

like image 182
oisti Avatar answered Oct 20 '22 15:10

oisti