UNPKG

react-enroute

Version:
60 lines (52 loc) 1.72 kB
import { cloneElement, Children } from 'react'; import { findPathValue } from './utils'; import { warnNotFound } from './debug'; export { genLocation, loc, isPath, findPath, findPathValue } from './utils'; export function Router(_ref) { var location = _ref.location, options = _ref.options, children = _ref.children; // null or undefined if (location == null) return null; var routes = addRoutes(children, {}); return renderMatch(routes, location, options); } function addRoutes(elements, routes, parent) { Children.forEach(elements, function (element) { var route = createRoute(element, parent); routes[route.path] = route; var children = element.props.children; addRoutes(children, routes, route); }); return routes; } function createRoute(element, parent) { var path = fullPath(element.props.path, parent); path = removeEdgeSlashes(path); return { path: path, parent: parent, element: element }; } function fullPath(path, parent) { if (!path) return parent ? parent.path : ''; // index route if (!parent || path[0] === '/') return path; // root or absolute return parent.path + '/' + path; } function renderMatch(routes, location, options) { location = removeEdgeSlashes(location); var result = findPathValue(routes, location, options); if (result) return render(result.value, result.params); warnNotFound(routes, location); return null; } function render(route, params, children) { var element = route.element, parent = route.parent; var node = cloneElement(element, params, children); return parent ? render(parent, params, node) : node; } function removeEdgeSlashes(path) { return path.replace(/^\/|\/$/g, ''); }