Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component} from 'react';
- import ReactDOM from 'react-dom';
- import PropTypes from 'prop-types';
- export class HashRouter extends Component {
- constructor(props) {
- super(props);
- this.checkHash = this.checkHash.bind(this);
- this.selectRoute = this.selectRoute.bind(this);
- window.onhashchange = this.checkHash.bind(this);
- this.state = {
- currentComponent : null,
- currentProps : {}
- };
- }
- parseUrl(url) {
- var parts = url.split("#");
- return parts[1] || "";
- }
- selectRoute(route) {
- var currentConfig;
- if (route === "") {
- route = "empty";
- }
- var checkRoute = typeof this.props.config[route];
- if (checkRoute === 'undefined' && route === 'notfound') {
- // prevent resursive endless loop
- console.warn(`HashRouter: undefined 'notfound' route. define a notfound route in your config to handle unknown routes`);
- return;
- }
- if (checkRoute === 'undefined') {
- currentConfig = this.selectRoute('notfound')
- } else if (checkRoute === 'string') {
- currentConfig = this.props.config[this.props.config[route]];
- } else if (checkRoute === 'object') {
- currentConfig = this.props.config[route];
- }
- return currentConfig
- }
- checkHash(h) {
- var oldRoute, route;
- if (h) {
- oldRoute = this.parseUrl(h.oldURL);
- route = this.parseUrl(h.newURL);
- } else {
- oldRoute = "";
- route = document.location.hash.substring(1);
- }
- document.body.id = route || "home";
- var routeInfo = this.selectRoute(route);
- var newProps = Object.assign({}, routeInfo.props || {}, {
- prevRoute: oldRoute,
- route : route
- });
- this.setState({
- currentComponent : routeInfo.component,
- currentProps : newProps
- });
- }
- componentWillMount() {
- this.checkHash();
- }
- render() {
- let ThisComp = <div />;
- if (this.state.currentComponent) {
- ThisComp = this.state.currentComponent;
- }
- console.log(<ThisComp {...this.state.currentProps} />);
- return (
- <ThisComp {...this.state.currentProps} />
- )
- }
- }
- HashRouter.propTypes = {
- config: PropTypes.object.isRequired
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement