CustomNavigation.jsx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import React, { useEffect, useState } from 'react';
  2. import PropTypes from 'prop-types';
  3. import {
  4. Nav, NavItem, NavLink, TabContent, TabPane,
  5. } from 'reactstrap';
  6. const CustomNavigation = (props) => {
  7. const [activeTab, setActiveTab] = useState('');
  8. // [TODO: set default active tab by gw4079]
  9. const [sliderWidth, setSliderWidth] = useState(null);
  10. const [sliderMarginLeft, setSliderMarginLeft] = useState(null);
  11. function switchActiveTab(activeTab) {
  12. setActiveTab(activeTab);
  13. }
  14. // Might make this dynamic for px, %, pt, em
  15. function getPercentage(min, max) {
  16. return min / max * 100;
  17. }
  18. useEffect(() => {
  19. if (activeTab === '') {
  20. return;
  21. }
  22. const navBar = document.getElementById('grw-custom-navbar');
  23. const navTabs = document.querySelectorAll('ul.grw-custom-navbar > li.grw-custom-navtab');
  24. if (navBar == null || navTabs == null) {
  25. return;
  26. }
  27. let tempML = 0;
  28. const styles = [].map.call(navTabs, (el) => {
  29. const width = getPercentage(el.offsetWidth, navBar.offsetWidth);
  30. const marginLeft = tempML;
  31. tempML += width;
  32. return { width, marginLeft };
  33. });
  34. const { width, marginLeft } = styles[props.navTabMapping[activeTab].index];
  35. setSliderWidth(width);
  36. setSliderMarginLeft(marginLeft);
  37. }, [activeTab]);
  38. return (
  39. <React.Fragment>
  40. <Nav className="nav-title grw-custom-navbar" id="grw-custom-navbar">
  41. {Object.entries(props.navTabMapping).map(([key, value]) => {
  42. return (
  43. <NavItem key={key} type="button" className={`p-0 grw-custom-navtab ${activeTab === key && 'active'}`}>
  44. <NavLink onClick={() => { switchActiveTab(key) }}>
  45. {value.icon}
  46. {value.i18n}
  47. </NavLink>
  48. </NavItem>
  49. );
  50. })}
  51. </Nav>
  52. <hr className="my-0 grw-nav-slide-hr border-none" style={{ width: `${sliderWidth}%`, marginLeft: `${sliderMarginLeft}%` }} />
  53. <TabContent activeTab={activeTab} className="p-4">
  54. {Object.entries(props.navTabMapping).map(([key, value]) => {
  55. return (
  56. <TabPane key={key} tabId={key}>
  57. {value.tabContent}
  58. </TabPane>
  59. );
  60. })}
  61. </TabContent>
  62. </React.Fragment>
  63. );
  64. };
  65. CustomNavigation.propTypes = {
  66. navTabMapping: PropTypes.object,
  67. };
  68. export default CustomNavigation;