Last active
May 31, 2017 14:39
-
-
Save ahlusar1989/e18c230f3a41c104b535713fbd760a48 to your computer and use it in GitHub Desktop.
Router Custom
This file contains hidden or 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
// Assuming you have a Component Dashboard, AnotherComponent, conditionally render based on props | |
const ROUTES = [ | |
{ | |
test: /\/another$/, | |
Component: Dashboard | |
}, | |
{ | |
test: /\/foo$/, | |
Component: Dashboard | |
}, | |
{ | |
test: /\/bar\/(\d|\D)*$/, | |
Component: AnotherComponent | |
} | |
]; | |
class Router extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
path: props.history.location.pathname, | |
previousPath: "/", | |
query: parseQueryString(props.history.location.search.substring(1)), | |
previousQuery: {} | |
}; | |
} | |
componentDidMount() { | |
this.detachHistory = this.props.history.listen(location => ( | |
this.setState({ | |
path: location.pathname, | |
previousPath: this.state.path, | |
query: parseQueryString(this.props.history.location.search.substring(1)), | |
previousQuery: this.state.query | |
}) | |
)); | |
} | |
componentWillReceiveProps(nextProps) { | |
if (nextProps.user && !this.props.user) { | |
console.log("AHHHHHHHHHH"); | |
} | |
} | |
componentWillUnmount() { | |
this.detachHistory(); | |
} | |
render() { | |
/* wait before rendering child components */ | |
if (!this.props.user) { | |
return null; | |
} | |
const Route = ROUTES.find(({ test }) => test.test(this.state.path)) || { Component: Dashboard }; | |
return <Route.Component {...this.state} {...this.props} />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment