Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you assign different values to the href element of NavLink in Chakra Navbar?

I want to give the href element in the NavLink component as the value of the Links array. Can I give a value to href using the map function?

To be clear, I would like to give the href elements of the NavLink function the values of ‘Home’, ‘Projects’, and ‘Careers’. (Not "#")

Link array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Links = ['Home', 'Projects', 'Careers'];

NavLink function

const NavLink = ({ children }: { children: ReactNode }) => (
  <Link
    px={2}
    py={1}
    rounded={'md'}
    _hover={{
      textDecoration: 'none',
      bg: useColorModeValue('#00afff', '#00afff'),
    }}
    href={'#'}
  >
    {children}
  </Link>
);

Components Used

<HStack spacing={8} alignItems={'center'}>
  <NavBarLogo src= {HdhLogo} />
  <HStack
    as={'nav'}
    spacing={4}
    display={{ base: 'none', md: 'flex' }}>
    {Links.map((link) => (
      <NavLink key={link}>{link}</NavLink>
    ))}
  </HStack>
</HStack>

>Solution :

Since the Links array is an array of strings

const Links = ['Home', 'Projects', 'Careers'];

that are passed as children

{Links.map((link) => (
  <NavLink key={link}>
    {link}
  </NavLink>
))}

Just pass the children prop to the href prop

const NavLink = ({ children }: { children: ReactNode }) => (
  <Link
    px={2}
    py={1}
    rounded={'md'}
    _hover={{
      textDecoration: 'none',
      bg: useColorModeValue('#00afff', '#00afff'),
    }}
    href={children}
  >
    {children}
  </Link>
);

It may be better to expose an href prop on the NavLink component though.

const NavLink = ({ children, href }: { children: ReactNode, href: string }) => (
  <Link
    px={2}
    py={1}
    rounded={'md'}
    _hover={{
      textDecoration: 'none',
      bg: useColorModeValue('#00afff', '#00afff'),
    }}
    href={href}
  >
    {children}
  </Link>
);

{Links.map((link) => (
  <NavLink key={link} href={link}>
    {link}
  </NavLink>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading