Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5189

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T06:55:07+00:00 2024-11-27T06:55:07+00:00

Handling Icons in React: Best Practices

  • 61k

Throughout my experience developing websites with React, I frequently encountered challenges with icons (especially those not sourced from libraries). One key question was: How can I handle my icons more efficiently in code?

Why I Switched to SVGs

Initially, I used PNG and JPEG files for icons, but quickly realized their limitations. Switching to SVG files offered several advantages:

  • Scalability: SVGs can scale without losing quality.
  • Faster Loading: SVG files are lightweight, improving load times.
  • CSS Styling: SVGs can be easily styled directly in CSS.

Creating Icon Components

After adopting SVGs, I structured my icon components like this:

export const ExampleIcon: React.FC = () => {   return (     <svg>       { /* svg code here */ }     </svg>   ); }; 
Enter fullscreen mode Exit fullscreen mode

While this worked, I wanted more flexibility in styling and leveraging React’s component power. To achieve that, I added props to my icon components:

export const ExampleIcon: React.FC<SVGProps<SVGSVGElement>> = (props) => {   return (     <svg {...props}>       { /* svg code here */ }     </svg>   ); }; 
Enter fullscreen mode Exit fullscreen mode

This allows us to pass all standard svg element props to our icons.

Organizing Icons in React

To keep my icons organized, I created an icons folder and added a new component whenever I needed a new icon. This method worked for a while, but I wondered—is there a more efficient approach?

Discovering @svgr/cli

After researching best practices, I came across @svgr/cli, a game-changing tool for handling SVGs in React. This CLI tool automatically generates React components from SVG files, saving time and improving maintainability.

Generating Icon Components Automatically

Instead of manually creating icon components, I could now run a single command to generate them:

npx @svgr/cli icons/svgs --out-dir icons/components --typescript

This command converts all SVG files in the svgs folder into TypeScript React components, placing them in the icons/components folder.

Building a Flexible Icon Component

To streamline the use of icons, I built a reusable Icon component. Here’s the folder structure I used:

src/   components/     icons/   svgs/   types/ 
Enter fullscreen mode Exit fullscreen mode

  • components/icons/: Contains generated icon components.
  • svgs/: Stores raw SVG files.
  • types/: Holds TypeScript types, including icon-type.ts.

Step 1: Define Icon Type

In src/types/icon-type.ts, I defined the type for our icon components:

import type * as Icons from '../components/icons';  export type IconType = keyof typeof Icons; 
Enter fullscreen mode Exit fullscreen mode

This type ensures that IconType corresponds to the names of the generated components, such as Logo for a Logo.tsx component.

Step 2: Create the Icon Component

Next, I created the Icon.tsx file in src/components/:

import React, { type SVGProps } from 'react'; import type { IconType } from '../types/icon-type'; import * as Icons from './icons';  export type IconProps = SVGProps<SVGSVGElement> & {   icon: IconType; };  export const Icon: React.FC<IconProps> = ({ icon, ...props }) => {   const Component = React.createElement(Icons[icon], props);    return (     <span className="custom-icon">       {Component}     </span>   ); }; 
Enter fullscreen mode Exit fullscreen mode

This component dynamically renders the appropriate icon based on the icon prop. For instance, to display the Logo icon, you would use:

export const TestComponent: React.FC = () => {   return (     <div>       <Icon icon="Logo" />     </div>   ); }; 
Enter fullscreen mode Exit fullscreen mode

Step 3: Styling the Icons

To ensure icons inherit the current text color, add the following to your global CSS file:

.custom-icon path, .custom-icon rect {   stroke: currentColor; } 
Enter fullscreen mode Exit fullscreen mode

Automating Icon Generation

To simplify the process, I added the following script to my package.json file:

"icons:generate": "npx @svgr/cli src/svgs --out-dir src/components/icons --typescript" 
Enter fullscreen mode Exit fullscreen mode

The Final Flow

Whenever you need to add a new icon to your project, simply:

  1. Place the SVG file in the svgs folder.
  2. Run npm run icons:generate.
  3. Use the new icon by referencing it in the <Icon/> component with autocomplete support for icon names.

I hope this article helps you handle icons more effectively in your React projects. Feel free to ask any questions — I'd love to help! 😊

reacttutorialtypescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.