source: imaps-frontend/src/components/Profile/Profile.jsx@ 79a0317

main
Last change on this file since 79a0317 was 79a0317, checked in by stefan toskovski <stefantoska84@…>, 3 days ago

F4 Finalna Verzija

  • Property mode set to 100644
File size: 3.2 KB
Line 
1import React, { useState, useRef, useEffect } from "react";
2import ReactDOM from "react-dom";
3import { useNavigate } from "react-router-dom";
4import profile from "../../assets/person_icon.png";
5import styles from "./Profile.module.css";
6import { useAppContext } from "../AppContext/AppContext.jsx";
7
8function Profile({ position = "fixed" }) {
9 const { username, isAuthenticated } = useAppContext();
10 const [open, setOpen] = useState(false);
11 const [menuPosition, setMenuPosition] = useState({ top: 0, left: 0 });
12 const imgRef = useRef(null);
13 const navigate = useNavigate();
14
15 const menus = isAuthenticated ? ["My Maps", "Logout"] : ["Login"];
16
17 useEffect(() => {
18 const handleClickOutside = (e) => {
19 if (imgRef.current && !imgRef.current.contains(e.target)) {
20 setOpen(false);
21 }
22 };
23
24 document.addEventListener("click", handleClickOutside);
25
26 return () => {
27 document.removeEventListener("click", handleClickOutside);
28 };
29 }, []);
30
31 const toggleMenu = () => {
32 if (imgRef.current) {
33 const rect = imgRef.current.getBoundingClientRect();
34 setMenuPosition({
35 top: rect.bottom + window.scrollY,
36 left: rect.left + window.scrollX,
37 });
38 }
39 setOpen(!open);
40 };
41
42 const handleMenuClick = (menu) => {
43 if (menu === "My Maps") {
44 navigate("/MyMaps");
45 } else if (menu === "Logout") {
46 localStorage.removeItem("token");
47 window.location.reload();
48 } else if (menu === "Login") {
49 navigate("/Login");
50 }
51 setOpen(false);
52 };
53
54 const renderDropdown = () => {
55 if (!open) return null;
56
57 return ReactDOM.createPortal(
58 <div
59 className={styles.dropdownMenu}
60 style={{
61 position: "absolute",
62 top: menuPosition.top,
63 left: menuPosition.left,
64 }}
65 >
66 {isAuthenticated && <div className={styles.username}>{username}</div>}
67 <ul className={styles.menuList}>
68 {menus.map((menu) => (
69 <li
70 key={menu}
71 className={styles.menuItem}
72 onClick={() => handleMenuClick(menu)}
73 >
74 {menu}
75 </li>
76 ))}
77 </ul>
78 </div>,
79 document.body
80 );
81 };
82
83 return (
84 <div
85 className={
86 position === "fixed" ? styles.fixedProfileContainer : styles.inlineProfileContainer
87 }
88 >
89 <div className={styles.profileWrapper}>
90 <div
91 className={styles.profileIconContainer}
92 onClick={toggleMenu}
93 ref={imgRef}
94 >
95 <img src={profile} alt="profile" className={styles.profileImage} />
96 </div>
97 {renderDropdown()}
98 </div>
99 </div>
100 );
101}
102
103export default Profile;
Note: See TracBrowser for help on using the repository browser.