index.js
60 lines
| 1 | import {useState, useEffect, useRef} from 'react'; |
| 2 | import {useLocation} from 'react-router-dom'; |
| 3 | import {useSelector} from 'react-redux'; |
| 4 | import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; |
| 5 | |
| 6 | import './style.scss'; |
| 7 | |
| 8 | const MobileMenu = ({children}) => { |
| 9 | const [isOpen, setIsOpen] = useState(false); |
| 10 | |
| 11 | const contentRef = useRef(null); |
| 12 | |
| 13 | useEffect(() => { |
| 14 | const handleClick = (evt) => { |
| 15 | if (contentRef.current && !contentRef.current.contains(evt.target)) { |
| 16 | setIsOpen(false); |
| 17 | } |
| 18 | }; |
| 19 | |
| 20 | if (isOpen) { |
| 21 | document.addEventListener('click', handleClick); |
| 22 | } |
| 23 | |
| 24 | return function cleanup() { |
| 25 | if (isOpen) { |
| 26 | document.removeEventListener('click', handleClick); |
| 27 | } |
| 28 | }; |
| 29 | }, [isOpen, contentRef]); |
| 30 | |
| 31 | const location = useLocation(); |
| 32 | const tabsSelector = useSelector((state) => state.tabs); |
| 33 | |
| 34 | const slug = location.pathname.length > 2 ? location.pathname.split('/')[1] : 'dashboard'; |
| 35 | const label = tabsSelector[slug] ? tabsSelector[slug].label : null; |
| 36 | |
| 37 | return ( |
| 38 | <div className="give-donor-dashboard-mobile-menu"> |
| 39 | <div className="give-donor-dashboard-mobile-menu__header"> |
| 40 | <div className="give-donor-dashboard-mobile-menu__label">{label}</div> |
| 41 | <div |
| 42 | className={`give-donor-dashboard-mobile-menu__toggle ${ |
| 43 | isOpen ? 'give-donor-dashboard-mobile-menu__toggle--toggled' : '' |
| 44 | }`} |
| 45 | onClick={() => setIsOpen(!isOpen)} |
| 46 | > |
| 47 | <FontAwesomeIcon icon="bars" /> |
| 48 | </div> |
| 49 | </div> |
| 50 | {isOpen && ( |
| 51 | <div className="give-donor-dashboard-mobile-menu__content" ref={contentRef}> |
| 52 | {children} |
| 53 | </div> |
| 54 | )} |
| 55 | </div> |
| 56 | ); |
| 57 | }; |
| 58 | |
| 59 | export default MobileMenu; |
| 60 |