Home > Software design >  Custom icon wrapper component
Custom icon wrapper component

Time:02-25

I want to use react-feather icons but within a standard size button component I created.

To use a react-feather component I need to create it like so <Camera size={18} /> or <Icon.Camera size={18} /> however, I don't want to keep on repeating the size and color and any other prop that stays the same.

How can I make the icon type dynamic within my Button.

I know this form is invalid but I am looking for a way that is and that is the best I could write to present my thought.

import React, { FC } from "react";
import * as Icons from "react-feather";

interface IconProps {
  icon?: Icons.Icon;
}

const IconComponent: FC<IconProps> = (props) => {
  return (
    <button>
      {props.icon && <Icons[props.icon] size={18} />}
      {props.children}
    </button>
  );
};

export default IconComponent;

CodePudding user response:

The IconComponent component below should do. You can see it live in this codesandbox.

// Icon.tsx
import React, { ReactNode } from "react";
import { Icon } from "react-feather";

interface IconComponentProps {
  icon?: Icon;
  children: ReactNode;
}

const IconComponent = ({ icon: FeatherIcon, children }: IconComponentProps) => {
  return (
    <button>
      {FeatherIcon && <FeatherIcon size={18} />}
      {children}
    </button>
  );
};

export default IconComponent;

There you could use it anywhere:

// App.tsx
import IconComponent from "./Icon";
import { Camera, Airplay } from "react-feather";

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <IconComponent icon={Camera}>
        <h1>Camera</h1>
      </IconComponent>
      <IconComponent icon={Airplay}>
        <h1>Airlpay</h1>
      </IconComponent>
      <IconComponent>
        <h1>No Icon</h1>
      </IconComponent>
    </div>
  );
}
  • Related