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>
)
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With