Import icon as component instead as a svg file (React + Typescript)
As front end developers, part of our applications involves import icons in order to provide a better user interface. In most cases, we import icons for likes, comments, sidebar, notifications, etc. However, the hardest part is when specific behaviors are needed on those icons, like hover, color change, and other styles.
In this article, we will introduce a scenario which we import a single icon component instead import multiple svg files for make it more customizable.
Scenario
Let’s suppose we have a social media application and people press a like o favorite button on the posts. A specific requirement describe the favorite icon change the color depends of the number interaction.
In a common scenario, we usually to import all the svg files and write conditional for display each one.
As a show in the code, multiple imports is not the best practices for this case.
Let’s start to work with components!
We are going to use React-SVGR, a tool which convert svg code to a React component. For this case, we use a icon from Remix Icon and choose the heart icon and copy as svg.
After click on “Copy SVG”, we paste the code in React-SVGR and we have the following result.
Copy the React component and modified the code.
Then we modified our Post component with this Icon component.
There we have it! More clean and a single import in our Post component.
With this example, there are a lot of design rules which we can implement, like change the color when hover or click, change the icon if we want to be filled or outlined with css properties, add transition when change the style and what your imagination wants.
If you enjoyed this article, please share with your friends and a virtual clap👏 for more posts.
Thank you!
Resources:
- React SVGR
- Remix Icon
- SVG Properties and CSS