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
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>
CodePudding user response:
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>
))}