How can I make the active NavLink look similar to this? Tried following the react router dom docs but it didn’t give this desired look. Is it possible to pass the isActive prop from the NavLink component to the Flex component. I created a minimum representation of the sidebar down below. I’d appreciate any help.
Here’s a minimal recreation of the sidebar made using Chakra UI:
https://codesandbox.io/s/sidebar-ckm26m?file=/src/index.js
//imports
const App = () => {
return (
<Stack spacing={4}>
<NavLink to="/overview">
<Flex align="center" p="2" mx="2" ...>
<Box p="4px" border="1px" ...>
<AiOutlineDashboard size={16} />
</Box>
<Box ml={2} fontSize="sm">
Overview
</Box>
</Flex>
</NavLink>
<NavLink to="/app">
<Flex align="center" p="2" mx="2" ...>
<Box p="4px" border="1px" ...>
<IoApps size={16} />
</Box>
<Box ml={2} fontSize="sm">
Apps
</Box>
</Flex>
</NavLink>
</Stack>
)
}
export default App
2
Answers
Use a CSS selector with with pseudo class of active, within the pseudo class you can change the BG color
button:active {
background-color: green; /* Change the background color to green when the button is active /
border: 2px solid darkgreen; / Add a border to the button when it’s active */
}
You need to apply different styles based on your current path, one way of achieving this is by using
useLocation()
which gives you the current path.Make sure you make an array of your items so you can map over them and apply the necessary changes when it’s the selected path.
Now if I apply this concept to the code your provided on sandbox, my App.js should look like this
And it looks like that