r/learnreactjs • • Nov 15 '22

Generic button component with icons as props or children

Trying to build a generic button component with various icons as optional icons. Tips on how to achieve this?

6 Upvotes

1 comment sorted by

1

u/dev-beatss Nov 15 '22 edited Nov 15 '22

You could create an object holding all your icons like below:

    const buttonIcons = {
        "heart": <Heart size={32} />,
        "success": <Smiley size={32} />,
        "error": <Error size={32} />
    }

Create your Button component which has an icon prop and access the correct icon from your buttonIcons object using bracket notation:

const Button = (icon) => {
 return (
  <button>
    {buttonIcons[icon]}
  </button>
 )
}

Then simply pass in a string as a prop when you use the button to indicate which icon you want to use.

<Button icon="heart" />