I'm using [email protected]
but unable to style the NavLink
component backgroundColor when route is active. This works when I insert some text just below NavLink
tag.
import {
Box,
CloseButton,
Flex,
Icon,
useColorModeValue,
Drawer,
DrawerContent,
Text,
useDisclosure,
BoxProps,
FlexProps,
} from '@chakra-ui/react';
import {
FiHome,
FiCalendar,
FiBriefcase,
FiDollarSign,
} from 'react-icons/fi';
import {
IoPawOutline
} from 'react-icons/io5';
import { IconType } from 'react-icons';
import { NavLink, Outlet } from "react-router-dom";
import Navbar from './Navbar';
<NavLink
to={to}
style={({ isActive })=> ({
background: isActive ? "green" : "blue",
})}
>
<Flex
align="center"
p="4"
mx="4"
borderRadius={["4px"]}
role="group"
cursor="pointer"
_hover={{
bg: '#1D3EAC',
color: 'white',
}}
_active={{
bg: '#1D3EAC',
color: 'white',
}}
>
{icon && (
<Icon
mr="4"
fontSize="16"
_groupHover={{
color: 'white',
}}
as={icon}
/>
)}
{children}
</Flex>
</NavLink>
CodePudding user response:
You can use the children
render function of the NavLink
to conditionally set the background color of the Flex
component.
Example:
<NavLink to={to}>
{({ isActive }) => (
<Flex
align="center"
p="4"
mx="4"
borderRadius={["4px"]}
role="group"
cursor="pointer"
_hover={{
bg: "#1D3EAC",
color: "white"
}}
_active={{
bg: "#1D3EAC",
color: "white"
}}
color="white"
bg={isActive ? "green" : "blue"}
>
{icon && (
<Icon
mr="4"
fontSize="16"
_groupHover={{
color: "white"
}}
as={icon}
/>
)}
{children}
</Flex>
)}
</NavLink>
You could also render the Flex
component as
a NavLink
.
Example:
<Flex
as={NavLink}
to={to}
align="center"
p="4"
mx="4"
borderRadius={["4px"]}
role="group"
cursor="pointer"
_hover={{
bg: "#1D3EAC",
color: "white"
}}
_active={{
bg: "#1D3EAC",
color: "white"
}}
color="white"
style={({ isActive }) => ({
background: isActive ? "green" : "blue"
})}
>
{icon && (
<Icon
mr="4"
fontSize="16"
_groupHover={{
color: "white"
}}
as={icon}
/>
)}
{children}
</Flex>
CodePudding user response:
You can try to use function as a children for NavLink. One function params is boolean isActive
.
<NavLink to="/home">
{({ isActive }) => (
<span style={{ backgroundColor: isActive ? 'red' : 'blue'}}>link</span>
)}
</NavLink>