nav-link-with-prop
Version:
React Router NavLink that uses an active prop rather than css class.
63 lines (54 loc) • 2.81 kB
JavaScript
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React from 'react';
import { Link, Route } from 'react-router-dom';
import PropTypes from 'prop-types'; // TODO: prop for active
/**
* A Render Props wrapper that knows if it's "active" or not.
*/
function NavLinkWithProp(_ref) {
var exact = _ref.exact,
isActiveProp = _ref.isActive,
activeProp = _ref.activeProp,
location = _ref.location,
strict = _ref.strict,
to = _ref.to,
children = _ref.children,
rest = _objectWithoutPropertiesLoose(_ref, ["exact", "isActive", "activeProp", "location", "strict", "to", "children"]);
var path = typeof to === 'object' ? to.pathname : to; // Regex taken from: https://github.com/pillarjs/path-to-regexp/blob/master/index.js#L202
var escapedPath = path && path.replace(/([.+*?=^!:${}()[\]|/\\])/g, '\\$1');
return React.createElement(Route, {
path: escapedPath,
exact: exact,
strict: strict,
location: location
}, function (_ref2) {
var _objectSpread2;
var loc = _ref2.location,
match = _ref2.match;
var isActive = !!(isActiveProp ? isActiveProp(match, loc) : match);
return children(_objectSpread((_objectSpread2 = {}, _objectSpread2[activeProp] = isActive, _objectSpread2.to = to, _objectSpread2), rest));
});
}
NavLinkWithProp.propTypes = {
exact: Route.propTypes.exact,
isActive: PropTypes.func,
activeProp: PropTypes.string,
// eslint-disable-next-line react/forbid-prop-types
location: PropTypes.object,
strict: Route.propTypes.strict,
to: Link.propTypes.to,
children: PropTypes.func
};
NavLinkWithProp.defaultProps = {
exact: undefined,
isActive: undefined,
activeProp: 'active',
location: undefined,
strict: undefined,
to: undefined,
children: undefined
};
export default NavLinkWithProp;
//# sourceMappingURL=index.js.map