How to Create a Custom Next.js Link Component With Bootstrap Icon

How to Create a Custom Next.js Link Component With Bootstrap Icon

Next.js's next-link component is great for single-page web apps. Using next-link is great for speeding up navigation because instead of reloading the entire page, just the viewport is loaded with the new component(s).

I'm a regular user of react-bootstrap and I wanted a way to preceed my links with an icon. So, I thought I'd share with you a custom component I use regularly in my nav components.

Here's my custom component:

import Link from "next/link"; import * as Icon from 'react-bootstrap-icons'; export default function IconLink(props) { const IconInc = Icon[props.icon]; return ( <Link href={props.href} passHref> <a style={{ display: 'flex', flexDirection: 'row' }}> <IconInc style={{ marginTop: 'auto', marginBottom: 'auto', marginRight: '10px' }} /> <div style={{ marginTop: 'auto', marginBottom: 'auto' }}> {props.children} </div> </a> </Link> ); }

Now we can use this component in our nav components:

import IconLink from "./iconLink"; import { Stack } from 'react-bootstrap' export default function Nav() { return ( <Stack gap={3}> <IconLink href="/" icon="HouseFill">Home</IconLink> <IconLink href="/forum" icon="CardList">Forum</IconLink> </Stack> ); }

This is the result:

Icon Link Result

I hope you found this useful. Thanks for reading!

Please Share and Like!


About The Author

Jay Simons

Jay Simons

Jay is a full-stack developer, electrical engineer, writer and music producer. He currently resides in the Madison, WI area.

šŸ”—Linked In šŸ”—