I love using Chakra-ui, it's enabled me to develop faster and get my ideas down on the page so I can concentrate on other aspects of development. External links are not an issue to create, and Chakra isn't breaking any moulds with their implementation but the composability of their components allows for easy creation of a nice external link that uses an icon as its display piece. A library I like to use for icons is SimpleIcons, these are not your car, bird, desk or shop icons, rather a set of brand icons perfect for showing off what stack you currently indulge in or even as links to services you use. That will be our use case today, let's dive right in.
I'm going to assume you have Chakra-ui installed in your project.
Head to simple icons and grab yourself the GitHub icon (or whatever icon takes your fancy) and download it. These svgs are small, their paths are for the most part not complicated and so we can just keep our file handy until later. In your project create a new file and name it the name of your icon, I will name mine GitHub. We will be taking advantage of polymorphism and the
as prop which can be used on all Chakra primitives and enable us to set our generic Box component to act as an svg element semantically. (It's my understanding that all components derive from the Box component in Chakra). Import Box and set it as svg, then as children add the svg path that you downloaded earlier together with a title element.
One of the reasons I really like this approach to creating icons in my projects is that I can utilize the Chakra theme setup i have to alter the icon with user interaction. In the above code you can see that I have added an on hover event which will change the fill of the svg when the mouse hovers over it. You can of course include style tags in your svgs and there are other way to do the same but this is pure simplicity and reads very well in my opinion.
Now that we have our icon created we can create our external link. This wil really just be a wrapper around the native Chakra Link.
We pass in our icon as a child to the component meaning the icon will render instead of any text. When the user hovers over the icon they will be able to read the title element text we set in the icon component. By setting the
isExternal prop on the component we are telling Chakra to add some defaults such as
rel. We also spread anything else we might want to pass in depending where we are rendering our component. As the Link component derives from the Box it inherits all of it's props so basically anything (style wise) can be passed onto it. Finally we pass in the href so that our link knows where to direct our users.
Using our new component is as simple as: