Creating a dynamic icons component on react
Managing icons in a React application can be challenging, especially when dealing with multiple icon types and dynamic rendering. Let's explore how to create a flexible and reusable Icons component that makes icon management a breeze.
Declaring the Icons Component
First, we'll create our Icons component in a TypeScript file. This component will serve as a central hub for all our application icons:
// @/components/icons.tsx
import { HomeIcon } from "lucide-react";
type IconProps = React.HTMLAttributes<SVGElement>;
export const Icons = {
logo: (props: IconProps) => {
return (
<svg>
{...props}
...
</svg>
);
},
home: (props: IconProps) => <HomeIcon {...props} />,
};
The component uses TypeScript to ensure type safety, defining IconProps as SVG element attributes.
Implementation and Usage
To use our Icons component effectively, we can create a type-safe implementation:
- Define an interface for items that will use icons
- Create a configuration array with icon mappings
- Implement dynamic icon rendering in your components
Example:
// Types and Configuration
interface ItemType {
title: string,
icon: string
}
const items: ItemType[] = [
{
title: "go to home"
icon: "home"
},
{
title: "Company logo"
icon: "logo"
}
]
// Component Implementation
const Something = ({ item } : { item: ItemType }) => {
const IconComponent = item.icon && Icons[item.icon]
return (
<div>
{IconComponent && IconComponent({
className: "size-6"
})}
</div>
)
}
By using this component structure, you can easily manage icons across your React app. The code is type-safe thanks to TypeScript and works smoothly with icon libraries like Lucide React.