Last active
November 19, 2017 20:49
-
-
Save oleg-am/e9254dc007362916a1e0862bb5657062 to your computer and use it in GitHub Desktop.
react-tabs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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