fabiobiondi

React Pro - Real World App - Ch7. 12. 12. Componente -IfLogged-- protezione DOM, Fragment and PropsW

Mar 17th, 2023
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // NavBar.tsx
  2. import { selectAuthIsLogged, useAuth } from '@/services/auth';
  3. import { NavLink, useNavigate } from 'react-router-dom';
  4. import logo from '../../../assets/laptop.png';
  5. import { selectCartIsEmpty, selectTotalCartItems, useCart, useCartPanel } from '@/services/cart';
  6. import { IfLogged } from '../auth/IfLogged';
  7. import { CartPanel } from './CartPanel';
  8.  
  9. const isActive = (obj: { isActive: boolean }) => {
  10.   return obj.isActive ? 'text-xl text-sky-400 font-bold' : 'text-xl text-white'
  11. }
  12.  
  13. export function NavBar() {
  14.   const navigate = useNavigate();
  15.   const logout = useAuth(state => state.logout);
  16.  
  17.   const isCartPanelOpened = useCartPanel(state => state.open);
  18.   const toggleCartPanel = useCartPanel(state => state.toggle);
  19.   const totalCartItems = useCart(selectTotalCartItems);
  20.   const isEmpty = useCart(selectCartIsEmpty);
  21.  
  22.   function logoutHandler() {
  23.     logout();
  24.     navigate('/login')
  25.   }
  26.  
  27.   return (
  28.     <div className="fixed top-0 left-0 right-0 shadow-2xl z-10">
  29.       <div className="bg-slate-900 flex justify-between items-center h-20 text-white p-3">
  30.  
  31.         {/*Logo*/}
  32.         <div className="flex items-center gap-3">
  33.           <img src={logo} alt="my logo" className="w-16"/>
  34.           <NavLink to="shop" className={isActive}>SHOP</NavLink>
  35.         </div>
  36.  
  37.         {/*Cart button badge*/}
  38.         <div>
  39.           <button disabled={isEmpty} className="btn accent lg" onClick={toggleCartPanel}>
  40.             Cart: {totalCartItems}
  41.           </button>
  42.         </div>
  43.  
  44.         {/*Cart Panel*/}
  45.         { isCartPanelOpened && <CartPanel/>}
  46.  
  47.  
  48.         {/*actions button*/}
  49.         <div className="fixed bottom-2 right-2 p-5">
  50.           <NavLink to="login" className="btn accent lg">login</NavLink>
  51.           <NavLink to="cms" className="btn accent lg">cms</NavLink>
  52.           <IfLogged>
  53.             <button onClick={logoutHandler} className="btn primary lg">logout</button>
  54.           </IfLogged>
  55.         </div>
  56.  
  57.       </div>
  58.     </div>
  59.   )
  60. }
  61.  
Add Comment
Please, Sign In to add comment