More concise breadcrumb generation

Courtesy of @hafriedlander
This commit is contained in:
Ingo Schommer 2016-04-07 22:55:08 +12:00
parent 2f801f9319
commit f9d5b0db97
2 changed files with 14 additions and 18 deletions

View File

@ -20,21 +20,15 @@ class NorthHeaderBreadcrumbsComponent extends SilverStripeComponent {
return null;
}
const breadcrumbs = this.props.crumbs.map((crumb, index, crumbs) => {
let component;
// If its the last item in the array
if (index === crumbs.length - 1) {
component = <span key={index} className="crumb last">{crumb.text}</span>;
} else {
component = [
<a key={index} className="cms-panel-link crumb" href={crumb.href}>{crumb.text}</a>,
<span className="sep">/</span>,
];
}
return component;
});
return breadcrumbs;
return [].concat(
this.props.crumbs.slice(0, -1).map((crumb, index) => [
<a key={index} className="cms-panel-link crumb" href={crumb.href}>{crumb.text}</a>,
<span className="sep">/</span>,
]),
this.props.crumbs.slice(-1).map((crumb, index) => [
<span key={index} className="crumb last">{crumb.text}</span>,
])
);
}
}

View File

@ -17,16 +17,18 @@ describe('NorthHeaderBreadcrumbsComponent', () => {
it('should convert the props.crumbs array into jsx to be rendered', () => {
props.crumbs = [
{ text: 'breadcrumb1', href: 'href1'},
{ text: 'breadcrumb2', href: 'href2'}
{ text: 'breadcrumb2', href: 'href2'},
{ text: 'breadcrumb3', href: 'href3'}
];
northHeaderBreadcrumbs = ReactTestUtils.renderIntoDocument(
<NorthHeaderBreadcrumbsComponent {...props} />
);
expect(northHeaderBreadcrumbs.getBreadcrumbs()[0][0].props.children).toBe('breadcrumb1');
expect(northHeaderBreadcrumbs.getBreadcrumbs()[0][1].props.children).toBe('/');
expect(northHeaderBreadcrumbs.getBreadcrumbs()[1].props.children).toBe('breadcrumb2');
expect(northHeaderBreadcrumbs.getBreadcrumbs()[1][0].props.children).toBe('breadcrumb2');
expect(northHeaderBreadcrumbs.getBreadcrumbs()[1][1].props.children).toBe('/');
expect(northHeaderBreadcrumbs.getBreadcrumbs()[2][0].props.children).toBe('breadcrumb3');
});
it('should return null if props.crumbs is not set', () => {