refactor wrapped nav components to expandable nav group component

This commit is contained in:
Jake McDermott
2018-12-14 04:02:44 -05:00
parent 9114c16a97
commit 5d4aa56f4a
4 changed files with 101 additions and 206 deletions

View File

@@ -1,44 +0,0 @@
import React, { Component } from 'react';
import {
withRouter
} from 'react-router-dom';
import {
NavExpandable,
NavItem,
} from '@patternfly/react-core';
class NavExpandableWrapper extends Component {
constructor (props) {
super(props);
// introspect to get any child 'NavItem' components
const { children } = this.props;
const navItems = children.filter(({ type }) => type.componentType === NavItem.displayName);
// Extract a list of 'to' params from the nav items and store it for later. This will create
// an array of the url paths associated with any child NavItem components.
this.navItemPaths = navItems.map(item => item.props.to.replace('/#', ''));
}
isActiveGroup = () => {
const { history } = this.props;
return this.navItemPaths.some(path => history.location.pathname.includes(path));
};
render () {
const { children, staticContext, ...rest } = this.props;
const isActive = this.isActiveGroup();
return (
<NavExpandable
isActive={isActive}
isExpanded={isActive}
{...rest}
>
{ children }
</NavExpandable>
);
}
}
export default withRouter(NavExpandableWrapper);

View File

@@ -0,0 +1,53 @@
import React, { Component } from 'react';
import {
withRouter
} from 'react-router-dom';
import {
NavExpandable,
NavItem,
} from '@patternfly/react-core';
class NavExpandableGroup extends Component {
constructor (props) {
super(props);
const { routes } = this.props;
// Extract a list of paths from the route params and store them for later. This creates
// an array of url paths associated with any NavItem component rendered by this component.
this.navItemPaths = routes.map(({ path }) => path);
}
isActiveGroup = () => this.navItemPaths.some(this.isActivePath);
isActivePath = (path) => {
const { history } = this.props;
return history.location.pathname.includes(path);
};
render () {
const { routes, groupId, staticContext, ...rest } = this.props;
const isActive = this.isActiveGroup();
return (
<NavExpandable
isActive={isActive}
isExpanded={isActive}
groupId={groupId}
{...rest}
>
{routes.map(({ path, title }) => (
<NavItem
groupId={groupId}
isActive={this.isActivePath(path)}
key={path}
to={`/#${path}`}
>
{title}
</NavItem>
))}
</NavExpandable>
);
}
}
export default withRouter(NavExpandableGroup);

View File

@@ -1,7 +0,0 @@
import React from 'react';
import { withRouter } from 'react-router-dom';
import { NavItem } from '@patternfly/react-core';
export default withRouter(({ history, to, staticContext, ...props }) => (
<NavItem to={to} isActive={history.location.pathname.includes(to.replace('/#', ''))} {...props} />
));