Skip to content

Instantly share code, notes, and snippets.

@oleg-am
Last active November 19, 2017 20:49
Show Gist options
  • Save oleg-am/e9254dc007362916a1e0862bb5657062 to your computer and use it in GitHub Desktop.
Save oleg-am/e9254dc007362916a1e0862bb5657062 to your computer and use it in GitHub Desktop.
react-tabs
import React, { Component } from 'react';
import { Switch, Route, Redirect, withRouter } from 'react-router-dom';
import Loadable from 'react-loadable';
const tabs = require('../tabs.json');
class Routes extends Component {
state = {}
componentDidMount() {
const { location: { pathname } } = this.props;
this.loadComponent(pathname);
}
componentWillReceiveProps(next) {
const { location: { pathname } } = this.props;
const { location: { pathname: nextPathname } } = next;
if (pathname !== nextPathname) {
this.loadComponent(nextPathname)
}
}
loadComponent(pathname) {
const tab = tabs.find(tab => pathname === `/${tab.id}`);
if (tab && !this.state[tab.id]) {
import(`./${tab.path}`).then(Comp => {
this.setState({ [tab.id]: Comp.default });
});
}
}
render() {
return (
<div className="content">
<main>
<Switch>
{tabs.map(tab => (
<Route
key={tab.id}
path={`/${tab.id}`}
render={props => {
const Tab = this.state[tab.id];
return (
Tab
? <Tab />
: <span>Is loading ... </span>
);
}} />
))}
<Redirect to="/dummyTable"/>
</Switch>
</main>
</div>
)
}
}
export default withRouter(Routes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment