TL DR;
Assuming that you're trying to map it to URLs, the trick in here, is to programatically set the "value" property of <Tab> to the one that the URL currently has. I'm going to assume you're using React Router.
Example:
const baseUrls = ['', 'online-manga-reader', 'admin'];
class TabBar extends React.Component {
constructor(props) {
super(props);
this.state = {
value: this.processPathName(),
};
}
processPathName(){
const path = this.props.location.pathname.split('/')[1];
const value = baseUrls.indexOf(path);
return value !== -1 ? value : 0; // This is the default one.
}
handleChange = (event, value) => {
this.setState({ value });
this.returnTabContainer(value);
}
returnTabContainer(value) {
switch (value) {
case 1:
this.props.history.push('/online-manga-reader');
break;
case 2:
this.props.history.push('/admin/article');
break;
default:
this.props.history.push('/');
}
}
returnTabAdmin() {
return this.props.isAdmin ? <Tab label="Admin Tab" /> : '';
}
render() {
const { classes } = this.props;
const { value } = this.state;
return (
<div className={classes.root}>
<AppBar position="static">
<Tabs
value={value}
onChange={(evt, val) => {this.handleChange(evt, val); }}
>
<Tab label="Home" />
<Tab label="Online Manga Reader" />
{this.returnTabAdmin()}
</Tabs>
<LoginButton />
</AppBar>
</div>
);
}
}
export default connect(mapStateToProps)(withStyles(styles)(withRouter(TabBar)));
Explanation
const baseUrls = ['', 'online-manga-reader', 'admin'];
This is an array that lives outside the class, and holds the first path of the URL (Or the base URL):
This will match the base URL (hence the first one will be selected)
http://example.com/
This one, the second will be matched
The third one:
- http://example.com/admin
- http://example.com/admin/article/create
The "trick" that I'm using in here lies in the processPathName() method.
It reads from React-Router the current URL, then it calls the split, which will already have the URL parsed to you in the pieces needed:
http://example.com/admin/article/create
Will translate to:
/ admin article create
Always returning us in the position 1 the one that we're looking for (this is one from the split).
With that, we use the good ol' indexOf to search inside the array for our path. If it finds it, it's going to return the number that is going to match the position of our tabs. That's why it's important for them to be in the same order.
If by any chance it doesn't find it, we set a default value (in this case we set it for zero, which accounts for the Home Page).
Your items should render normally, without any issues.
<Tabs>and<Tab>components work ie: What happens in<Tabs>when you click on a given tab? - Drum