UNPKG

@eolme/vma-router

Version:
29 lines (28 loc) 1.11 kB
import React from 'react'; import { useContext, useState, useEffect } from '@eolme/vma-engine'; import { RouterContext } from '../components/RouterContext'; import { error } from '../utils/report'; export function withRouter(Component) { const withRouter = (props) => { /* eslint-disable react-hooks/rules-of-hooks */ const router = useContext(RouterContext); if (!router) { error('Missing router context!'); return null; } const [route, setRoute] = useState(router.history.route); useEffect(() => { const fn = (event) => { setRoute(event.next); }; router.history.on('update', fn); return () => { router.history.off('update', fn); }; }, [router]); return (React.createElement(Component, Object.assign({}, props, { route: route }))); }; const displayName = Component.displayName || Component.name || 'Component'; withRouter.displayName = `withRouter${displayName})`; return withRouter; }