PagePath.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import React from 'react';
  2. export default class PagePath extends React.Component {
  3. constructor(props) {
  4. super(props);
  5. this.state = {
  6. pages: [],
  7. isListPage: false,
  8. };
  9. }
  10. componentWillMount() {
  11. // whether list page or not
  12. const isListPage = this.props.pagePath.match(/\/$/);
  13. this.setState({ isListPage });
  14. // generate pages obj
  15. let splitted = this.props.pagePath.split(/\//);
  16. splitted.shift(); // omit first element with shift()
  17. if (splitted[splitted.length-1] === '') {
  18. splitted.pop(); // omit last element with unshift()
  19. }
  20. let pages = [];
  21. let parentPath = '/';
  22. splitted.forEach((pageName) => {
  23. pages.push({
  24. pagePath: parentPath + pageName,
  25. pageName: pageName,
  26. });
  27. parentPath += pageName + '/';
  28. });
  29. this.setState({ pages });
  30. }
  31. render() {
  32. const pageLength = this.state.pages.length;
  33. const afterElements = [];
  34. this.state.pages.forEach((page, index) => {
  35. const isLastElement = (index == pageLength-1);
  36. // add elements
  37. afterElements.push(
  38. <span key={page.pagePath} className="path-segment">
  39. <a href={page.pagePath}>{page.pageName}</a>
  40. </span>);
  41. afterElements.push(
  42. <span key={page.pagePath+'/'} className="separator">
  43. <a href={page.pagePath+'/'} className={(isLastElement && !this.state.isListPage) ? 'last-path' : ''}>/</a>
  44. </span>
  45. );
  46. });
  47. return (
  48. <span className="page-path">
  49. <span className="separator">
  50. <a href="/">/</a>
  51. </span>
  52. {afterElements}
  53. </span>
  54. );
  55. }
  56. }
  57. PagePath.propTypes = {
  58. pagePath: React.PropTypes.string.isRequired,
  59. };