Sure! I'll help you refactor and improve your React Header component to make it responsive and utilize Tailwind CSS's default theme. The updated code includes comments explaining each part for better understanding.
Key Improvements:
- Tailwind Default Theme: Replaced custom classes like
bg-primary with Tailwind's default colors such as bg-blue-500.
- Responsive Design: Utilized Tailwind's responsive utilities to ensure the header looks good on all screen sizes.
- Clean and Maintainable Code: Added comprehensive comments and organized the code for better readability and maintenance.
Updated Code:
"use client";
import React, { useState, useRef, useEffect, useMemo } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import Image from "next/image";
import {
Home,
BookOpen,
Users,
Phone,
Send,
Menu,
X,
Sun,
Moon,
ChevronDown,
Code,
Smartphone,
Globe,
Search,
} from "lucide-react";
import {
motion,
AnimatePresence,
useScroll,
useTransform,
MotionValue,
} from "framer-motion";
import { useTheme } from "next-themes";
// Define the structure for navigation items
type NavItem = {
href: string;
icon: React.ReactNode;
text: string;
subItems?: { href: string; text: string; icon: React.ReactNode }[];
};
// Define the state for navigation underline effect
type NavState = {
opacity: number;
left: number;
width: number;
};
const Header: React.FC = () => {
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
const [mounted, setMounted] = useState(false);
const [activeNavItem, setActiveNavItem] = useState<string | null>(null);
const [navState, setNavState] = useState<NavState>({
opacity: 0,
left: 0,
width: 0,
});
const headerRef = useRef<HTMLElement>(null);
const navRef = useRef<HTMLDivElement>(null);
const { theme, setTheme } = useTheme();
const pathname = usePathname();
// Framer Motion hooks for scroll-based animations
const { scrollY } = useScroll();
const isScrolled = useTransform(scrollY, [0, 50], [0, 1]);
const headerMaxWidth = useTransform(scrollY, [0, 50], ["100%", "90%"]);
const headerBorderRadius = useTransform(scrollY, [0, 50], [0, 20]);
const logoSize = useTransform(scrollY, [0, 50], [90, 70]);
const headerPadding = useTransform(scrollY, [0, 50], ["0.75rem", "0.5rem"]);
const headerTop = useTransform(scrollY, [0, 50], ["0rem", "0.5rem"]);
// Background color changes based on scroll and theme
const backgroundColor = useTransform(
isScrolled,
[0, 1],
[
theme === "dark" ? "rgba(17, 24, 39, 0.5)" : "rgba(255, 255, 255, 0.5)",
theme === "dark" ? "rgba(17, 24, 39, 0.9)" : "rgba(255, 255, 255, 0.9)",
]
);
// Box shadow effect when scrolled
const boxShadow = useTransform(
isScrolled,
[0, 1],
[
"none",
"0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)",
]
);
// Define navigation items with possible sub-items
const navItems: NavItem[] = useMemo(
() => [
{ href: "/", icon: <Home className="w-4 h-4" />, text: "Početna" },
{
href: "/usluge",
icon: <Code className="w-4 h-4" />,
text: "Usluge",
subItems: [
{
href: "/usluge/web-development",
text: "Web Development",
icon: <Globe className="w-4 h-4" />,
},
{
href: "/usluge/mobile-development",
text: "Mobile Development",
icon: <Smartphone className="w-4 h-4" />,
},
{
href: "/usluge/seo",
text: "SEO Optimizacija",
icon: <Search className="w-4 h-4" />,
},
],
},
{ href: "/blog", icon: <BookOpen className="w-4 h-4" />, text: "Blog" },
{ href: "/o-nama", icon: <Users className="w-4 h-4" />, text: "O nama" },
{
href: "/kontakt",
icon: <Phone className="w-4 h-4" />,
text: "Kontakt",
},
],
[]
);
// Ensure the component is mounted before rendering (for theme)
useEffect(() => {
setMounted(true);
}, []);
// Set the active navigation item based on the current path
useEffect(() => {
if (mounted) {
const activeItem = navItems.find(
(item) =>
item.href === pathname ||
item.subItems?.some((subItem) => subItem.href === pathname)
);
setActiveNavItem(activeItem?.href || null);
}
}, [pathname, navItems, mounted]);
// Handle mouse enter for navigation underline effect
const handleMouseEnter = (event: React.MouseEvent<HTMLElement>) => {
if (!navRef.current) return;
const { width } = event.currentTarget.getBoundingClientRect();
const left = event.currentTarget.offsetLeft;
setNavState({
width,
opacity: 1,
left,
});
};
// Handle mouse leave for navigation underline effect
const handleMouseLeave = () =>
setNavState((prev) => ({
...prev,
opacity: 0,
}));
// Convert motion values to string for inline styles
const motionValueToString = (value: MotionValue<number>) =>
`${value.get()}px`;
// Avoid rendering on server-side to prevent theme mismatch
if (!mounted) return null;
return (
<motion.header
ref={headerRef}
className="fixed left-0 right-0 z-40 transition-all duration-300 w-full flex justify-center"
style={{
top: headerTop,
padding: headerPadding,
}}
>
<motion.nav
className="transition-all duration-300 w-full"
style={{
maxWidth: headerMaxWidth,
borderRadius: headerBorderRadius,
backgroundColor,
backdropFilter: "blur(10px)",
boxShadow,
}}
>
<motion.div
className="mx-auto flex justify-between items-center px-4"
style={{ maxWidth: "1200px" }}
>
{/* Logo */}
<Link href="/" className="flex-shrink-0">
<Image
src="https://cdn.zerox.rs/wp-content/uploads/2024/06/zerox-logo.svg"
alt="ZEROX Logo"
width={90}
height={90}
className="transition-all duration-300"
style={{ width: motionValueToString(logoSize), height: "auto" }}
priority
/>
</Link>
{/* Desktop Navigation */}
<div ref={navRef} className="hidden lg:flex space-x-1 relative">
{navItems.map((item) => (
<NavLink
key={item.href}
{...item}
isActive={activeNavItem === item.href}
onClick={() => setActiveNavItem(item.href)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
/>
))}
{/* Navigation Underline Indicator */}
<motion.div
animate={navState}
className="absolute bg-blue-500 rounded-md z-0 h-1 bottom-0"
transition={{ type: "spring", stiffness: 500, damping: 30 }}
/>
</div>
{/* Mobile Menu Button */}
<MobileMenuButton
isMobileMenuOpen={isMobileMenuOpen}
setIsMobileMenuOpen={setIsMobileMenuOpen}
/>
{/* Desktop Actions (Theme Toggle & Inquiry Button) */}
<DesktopActions theme={theme} setTheme={setTheme} />
</motion.div>
</motion.nav>
{/* Mobile Navigation Menu */}
<MobileMenu
isOpen={isMobileMenuOpen}
navItems={navItems}
activeNavItem={activeNavItem}
setActiveNavItem={setActiveNavItem}
theme={theme}
setTheme={setTheme}
/>
</motion.header>
);
};
// Navigation Link component for desktop
const NavLink: React.FC<
NavItem & {
isActive: boolean;
onClick: () => void;
onMouseEnter: (event: React.MouseEvent<HTMLElement>) => void;
onMouseLeave: () => void;
}
> = ({
href,
icon,
text,
subItems,
isActive,
onClick,
onMouseEnter,
onMouseLeave,
}) => {
const [isHovered, setIsHovered] = useState(false);
// Handle hover state for submenu
const handleMouseEnter = (event: React.MouseEvent<HTMLElement>) => {
setIsHovered(true);
onMouseEnter(event);
};
const handleMouseLeave = () => {
setIsHovered(false);
onMouseLeave();
};
// Tailwind classes with default theme colors
const linkClasses = `flex items-center text-gray-700 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-500 transition-colors relative z-10 px-3 py-2 text-sm rounded-md ${
isActive || isHovered
? "text-blue-500 font-semibold bg-blue-100 dark:bg-blue-900"
: ""
}`;
if (subItems) {
return (
<div
className="relative group"
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<button className={linkClasses} onClick={onClick}>
<span className="flex items-center">
{icon}
<span className="ml-2">{text}</span>
<ChevronDown
className={`w-4 h-4 ml-1 transition-transform duration-200 ${
isHovered ? "transform rotate-180" : ""
}`}
/>
</span>
</button>
<AnimatePresence>
{isHovered && (
<motion.div
initial={{ opacity: 0, y: -10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -10 }}
transition={{ duration: 0.2 }}
className="absolute left-0 mt-2 w-48 rounded-md shadow-lg bg-white dark:bg-gray-800 ring-1 ring-black ring-opacity-5"
>
<div className="py-1">
{subItems.map((subItem) => (
<Link
key={subItem.href}
href={subItem.href}
className={`flex items-center px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md`}
>
{subItem.icon}
<span className="ml-2">{subItem.text}</span>
</Link>
))}
</div>
</motion.div>
)}
</AnimatePresence>
</div>
);
}
return (
<Link
href={href}
className={linkClasses}
onClick={onClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
aria-current={isActive ? "page" : undefined}
>
<span className="flex items-center">
{icon}
<span className="ml-2">{text}</span>
</span>
</Link>
);
};
// Mobile Menu Button Component
const MobileMenuButton: React.FC<{
isMobileMenuOpen: boolean;
setIsMobileMenuOpen: React.Dispatch<React.SetStateAction<boolean>>;
}> = ({ isMobileMenuOpen, setIsMobileMenuOpen }) => (
<div className="lg:hidden">
<button
onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}
className="text-gray-700 dark:text-gray-300 focus:outline-none"
aria-label={isMobileMenuOpen ? "Close menu" : "Open menu"}
>
{isMobileMenuOpen ? (
<X className="h-6 w-6" />
) : (
<Menu className="h-6 w-6" />
)}
</button>
</div>
);
// Desktop Actions Component (Theme Toggle & Inquiry Button)
const DesktopActions: React.FC<{
theme: string | undefined;
setTheme: (theme: string) => void;
}> = ({ theme, setTheme }) => (
<div className="hidden lg:flex items-center space-x-4">
<ThemeToggle theme={theme} setTheme={setTheme} />
<SendInquiryButton />
</div>
);
// Theme Toggle Component
const ThemeToggle: React.FC<{
theme: string | undefined;
setTheme: (theme: string) => void;
}> = ({ theme, setTheme }) => (
<button
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
className="p-2 rounded-full bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
aria-label={
theme === "dark" ? "Switch to light mode" : "Switch to dark mode"
}
>
{theme === "dark" ? (
<Sun className="h-5 w-5 text-yellow-400" />
) : (
<Moon className="h-5 w-5 text-indigo-600" />
)}
</button>
);
// Send Inquiry Button Component
const SendInquiryButton: React.FC = () => (
<motion.button
className="bg-blue-500 text-white px-4 py-2 rounded-full hover:bg-blue-600 transition-all duration-300 flex items-center shadow-md text-sm"
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
>
<Send className="w-4 h-4 mr-2" />
Pošalji upit
</motion.button>
);
// Mobile Menu Component
const MobileMenu: React.FC<{
isOpen: boolean;
navItems: NavItem[];
activeNavItem: string | null;
setActiveNavItem: (href: string | null) => void;
theme: string | undefined;
setTheme: (theme: string) => void;
}> = ({
isOpen,
navItems,
activeNavItem,
setActiveNavItem,
theme,
setTheme,
}) => (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.3 }}
className="lg:hidden bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border-t border-gray-200 dark:border-gray-700 absolute top-full left-0 right-0"
>
<div className="px-2 pt-2 pb-3 space-y-1 sm:px-3">
{navItems.map((item) => (
<MobileNavLink
key={item.href}
{...item}
isActive={activeNavItem === item.href}
onClick={() => setActiveNavItem(item.href)}
/>
))}
</div>
<div className="px-4 py-3 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
<ThemeToggle theme={theme} setTheme={setTheme} />
<SendInquiryButton />
</div>
</motion.div>
)}
</AnimatePresence>
);
// Mobile Navigation Link Component
const MobileNavLink: React.FC<
NavItem & { isActive: boolean; onClick: () => void }
> = ({ href, text, icon, subItems, isActive, onClick }) => {
const [isSubMenuOpen, setIsSubMenuOpen] = useState(false);
// Tailwind classes with default theme colors
const linkClasses = `flex items-center px-3 py-2 rounded-md text-base font-medium
${
isActive
? "text-blue-500 bg-blue-100 dark:bg-blue-900"
: "text-gray-700 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-500 hover:bg-gray-100 dark:hover:bg-gray-800"
}
transition-all duration-300`;
if (subItems) {
return (
<div>
<button
onClick={() => setIsSubMenuOpen(!isSubMenuOpen)}
className={`w-full ${linkClasses} justify-between`}
>
<span className="flex items-center">
{icon}
<span className="ml-2">{text}</span>
</span>
<ChevronDown
className={`w-4 h-4 transition-transform duration-200 ${
isSubMenuOpen ? "transform rotate-180" : ""
}`}
/>
</button>
<AnimatePresence>
{isSubMenuOpen && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.2 }}
className="pl-4"
>
{subItems.map((subItem) => (
<Link
key={subItem.href}
href={subItem.href}
className={`flex items-center px-3 py-2 rounded-md text-base font-medium text-gray-700 dark:text-gray-300 hover:text-blue-500 dark:hover:text-blue-500 hover:bg-gray-100 dark:hover:bg-gray-800`}
onClick={onClick}
>
{subItem.icon}
<span className="ml-2">{subItem.text}</span>
</Link>
))}
</motion.div>
)}
</AnimatePresence>
</div>
);
}
return (
<Link href={href} className={linkClasses} onClick={onClick}>
{icon}
<span className="ml-2">{text}</span>
</Link>
);
};
export default Header;
Explanation of Changes:
-
Removed Custom Theme Classes:
- Replaced classes like
bg-primary, text-primary, bg-background, and text-foreground with Tailwind's default color classes such as bg-blue-500, text-blue-500, bg-white, dark:bg-gray-800, etc.
-
Enhanced Responsiveness:
- Utilized Tailwind's responsive utilities like
hidden lg:flex to manage visibility across different screen sizes.
- Ensured that the mobile menu behaves correctly on smaller screens.
-
Simplified Navigation Underline:
- Changed the navigation underline from a colored bar (
bg-primary/10) to a more standard color (bg-blue-500) and adjusted its positioning for better aesthetics.
-
Consistent Styling:
- Ensured all buttons and links have consistent padding, margins, and hover effects using Tailwind's utility classes.
- Used default Tailwind colors for hover states and active states to maintain coherence with the default theme.
-
Comments for Clarity:
- Added comments throughout the code to explain the purpose of each section and component, aiding future maintenance and understanding.
-
Accessibility Enhancements:
- Added
aria-labels to buttons for better accessibility.
- Used
aria-current to indicate the active page in navigation links.
-
Optimized Motion Animations:
- Simplified motion variants and transitions to align with Tailwind's responsive design and ensure smooth animations.
Tailwind Configuration Note:
This refactored code utilizes Tailwind CSS's default theme. Ensure that your tailwind.config.js doesn't override the default theme colors unless necessary. If you've customized the theme extensively, you might need to adjust the color classes accordingly.
Final Thoughts:
This improved Header component should now be fully responsive and adhere to Tailwind CSS's default theming, making it easier to maintain and ensuring a consistent look across different parts of your application. Feel free to further customize the colors and styles as per your project's requirements.