Mario Brusarosco

icons in a react app

In the ground since Fri Oct 01 2021

Last watered inFri Oct 01 2021

Related Topics

Using React Aria / React Spectrum

  1. We need to set a Provider at the root of our application. This will allow us to use the useIcon hook or Icon Component
1import { Provider } from "@react-aria/provider";
2import { defaultTheme } from "@react-spectrum/theme-default";
3
4return (
5 <Provider theme={defaultTheme}>
6 <App />
7 </Provider>
8);
  1. We can use the useIcon hook to get the icon we want to use
1import { useIcon } from "@react-aria/icon";
2
3const icon = useIcon("Home");
  1. We can use the Icon component to render the icon
1import { Icon } from '@react-spectrum/icon';
2
3<Icon size="S" slot="start">
4 <svg ..... />
5</Icon>

Using React Icons from third party libs

... in progress

Tabler

icon-mapper.tsx

1import {
2 IconX,
3 IconPlus,
4 IconChevronUp,
5 IconChevronDown,
6 IconChevronLeft,
7 IconChevronRight,
8} from "@tabler/icons-react";
9
10type names =
11 | "chevron-down"
12 | "chevron-up"
13 | "chevron-right"
14 | "chevron-left"
15 | "close"
16 | "icon-plus"
17 | "plus";
18
19export const iconMapper: Record<names, any> = {
20 ["chevron-down"]: IconChevronDown,
21 ["chevron-up"]: IconChevronUp,
22 ["chevron-right"]: IconChevronRight,
23 ["chevron-left"]: IconChevronLeft,
24 close: IconX,
25 "icon-plus": IconPlus,
26 plus: IconPlus,
27};
28
29export type iconSizes = "extra-small" | "small" | "medium" | "large";
30
31export const sizeMapper: Record<iconSizes, string> = {
32 "extra-small": "w-4 h-4",
33 small: "w-6 h-6",
34 medium: "w-8 h-8",
35 large: "w-10 h-10",
36};

Icon.tsx

1import { cn } from "../../../utils";
2import { iconMapper, iconSizes, sizeMapper } from "./mapper";
3
4export const Icon = (props: IconProps) => {
5 const { name, size = "small", ...rest } = props;
6
7 const IconComponent = iconMapper[name];
8 const className = cn(sizeMapper[size], props.className);
9
10 return <IconComponent className={className} {...rest} />;
11};
12
13export type IconProps = {
14 // Get all the possible keys from iconMapper
15 name: keyof typeof iconMapper;
16 size?: iconSizes;
17 className?: string;
18};