DEV Community

Gabriel Linassi
Gabriel Linassi

Posted on

How to create a polymorphic button in React

Today I want to show you how to build a polymorphic button. In other words, a button that may be a button, a external link or a link (route). For that I'll build a IconButton but it can be applied to anything else.

Instead of going with an approach like this which requires a lot more work, I will use RadixUI Slot component (~800B).

Implementation example:

/components/button-icon/ButtonIcon.tsx

import React from 'react'
import { Slot } from '@radix-ui/react-slot'

type AsButton = {
  asChild?: false
} & React.ComponentPropsWithoutRef<'button'>

type AsSlot = {
  asChild?: true
}

type ButttonIconProps = {
  children: React.ReactNode
} & (AsButton | AsSlot)

const ButtonIcon = ({ children, asChild, ...props }: ButttonIconProps) => {
  const Comp = asChild ? Slot : 'button'
  return (
    <Comp
      className="flex h-12 w-12 items-center justify-center rounded-lg border border-[#4A5465] bg-[#252932]"
      {...props}
    >
      {children}
    </Comp>
  )
}

export default ButtonIcon
Enter fullscreen mode Exit fullscreen mode

As you can see the code is much cleaner than this implementation

Usage sample

/pages/index.tsx

import type { NextPage } from 'next'
import NextLink from 'next/link'
import ButtonIcon from 'components/button-icon'
import { AppleIcon, FbIcon, GoogleIcon } from 'components/icons'

const HomePage: NextPage = () => {
  return (
    <div className="flex h-screen w-screen items-center justify-center bg-gray-600">
      <div className="flex h-80 w-full max-w-sm flex-col items-center justify-end rounded-md bg-gray-800 p-4">
        <div className="mt-4 flex gap-4">
          {/* link (route) */}
          <NextLink href="/account" passHref>
            <ButtonIcon asChild>
              <a>
                <AppleIcon />
              </a>
            </ButtonIcon>
          </NextLink>
          {/* external link */}
          <ButtonIcon asChild>
            <a
              href="https://www.linkedin.com/in/gabrielmlinassi/"
              target="_blank"
              rel="noreferrer"
            >
              <FbIcon />
            </a>
          </ButtonIcon>
          {/* button */}
          <ButtonIcon onClick={() => alert('clicked')}>
            <GoogleIcon />
          </ButtonIcon>
        </div>
      </div>
    </div>
  )
}

export default HomePage
Enter fullscreen mode Exit fullscreen mode

Stackblitz live code

Top comments (0)