Building Buttons

How to make a functional Button component

Michael Drotar
April 22, 2024 - 7 minutes

What is a Button

Components are a melding of form and functionality. Before I can talk about what a button component is, I need to tackle the low level functionality that it's meant to provide.

The HTML <button> tag has a type attribute to define 1 of 3 types of buttons:

  • type="submit" - submit a form
  • type="reset" - reset a form
  • type="button" - anything else, determined by its onClick handler

The HTML <a> tag, called an anchor, supports an href attribute to create links.

While links and buttons are fundamentally different, I'm mentioning them because it's common to have links that look like buttons. When talking with non-technical people, it's common to use language based on what something looks like rather than based on what function it performs.

This dichotomy is often over-looked. I've heard arguments that there's no difference between a link and a button that performs a redirect since they take the user to the same place in the end. I've also seen outdated practices still being used that assign a link to go nowhere and use javascript to perform an action when it's clicked.

I can understand how these practices functionally seem to work on the surface, but they omit the semantic aspect of HTML. And by doing so, they ignore the importance of accessibility. While that is a much larger discussion for another article, the important takeaway is that we should be building buttons that tackle all of this functionality so that developers can do the right thing by doing the simplest thing.

We should also note that this functionality is not unique to a single component. Most projects have a core button component, but they might also have other components for things like navigation that provide similar functionality. If we don't have a proper abstraction for this functionality, then it becomes very tempting to go down one of the earlier roads that break semantics.

Ready, Set, Action!

To encompass the details of something being an HTML link or an HTML button, I call this component an <Action>.

Unlike most components, this one is all functionality and no form. With this approach, higher level components no longer need to debate on which HTML tag to use. When given an href, it will be a link. Otherwise, it will be a button.

We'll get into a more robust implementation and some notes in a moment, but I want to cover the core functionality with a simple snippet first to demonstrate this.

1export function Action(props) {
2  const Tag = props.href ? Link : 'button'
3  return <Tag {...props } />
4}

Normally we think of <button> as the button tag. But under the hood, React has internal components that map with each HTML tag. You'll see in a moment how we import some attribute types from React. This is also why props like className differ from their HTML counterpart. I'm not sure what magic converts the "button" string to a component, but I'm sure it has something to do with why those components don't need to be imported like others do.

Imported components should be a little more straightforward. Since a component is just a function, there's nothing magical going on by assigning that function to another variable and using that variable to reference it later, even if it is referenced in the JSX part of the code. The JSX ultimately just calls the function it was given.

I wanted to demonstrate both types of components, but if you don't have a Link component then using "a" works just as well.

Here's the full implementation:

1import Link, { LinkProps } from 'next/link'
2import React, { AnchorHTMLAttributes, ButtonHTMLAttributes } from 'react'
3
4type RawButtonProps = Pick<
5  ButtonHTMLAttributes<HTMLButtonElement>,
6  'children' | 'className' | 'disabled' | 'onClick' | 'type'
7>
8
9type RawLinkProps = Pick<
10  AnchorHTMLAttributes<HTMLAnchorElement>,
11  'children' | 'className' | 'href' | 'onClick' | 'target'
12>
13
14type NextLinkProps = Pick<
15  LinkProps,
16  'onClick' | 'prefetch' | 'replace' | 'scroll'
17> & { href?: LinkProps['href'] }
18
19export type ActionProps = RawButtonProps &
20  (Omit<RawLinkProps, keyof NextLinkProps> & NextLinkProps)
21
22export function Action(props: ButtonProps) {
23  const {
24    children,
25    disabled,
26    type,
27    href,
28    target,
29    prefetch,
30    replace,
31    scroll,
32    ...restProps
33  } = props
34
35  const Component =
36    href && !disabled
37      ? (props: AnchorHTMLAttributes<HTMLAnchorElement>) => (
38          <Link {...props} {...{ href, target, prefetch, replace, scroll }} />
39        )
40      : (props: ButtonHTMLAttributes<HTMLButtonElement>) => (
41          <button {...props} {...{ disabled, type: type || 'button' }} />
42        )
43
44  return <Component {...restProps}>{children}</Component>
45}
46

Hopefully this is easy enough to break down: get the link and button types, combine them, and create a component that takes the props of both to decide which one to render.

When building components from this Action component, it's important to note that browser stylesheets will make the underlying HTML links and buttons look different. Be sure to test both or use a proper css reset to make them the same.

There are also a number of choices that I made based on what I have found works best for me and people I have worked with, so I'll note those below:

  • HTML buttons and anchors have huge lists of attributes. I'm using Pick<> to only support a finite list of them. I generally encourage to start small and add things as needed over time since smaller lists are much easier for developers to look through.
  • I'm extending the Next.js Link component because it's what I'm familiar with. If you're using a different component then you may need to adapt some things. If you want to use a raw HTML link then just drop those parts.
  • In HTML, a link cannot be disabled, but a button can be. Since an Action component is both, I thought it was more intuitive to allow it. However, think twice if disabling a link is really the most semantic thing to do. Most times I've seen developers reach for CSS pointer events or other ways of disabling links, there's been a better solution available. By choosing to support them, I can later audit them if need be rather than encourage people to reach for some other one-off solution that'll be buried in the codebase.
  • HTML buttons inside of forms default to being a submit button. I've found it more intuitive to default all buttons to being standard buttons instead. When creating a button that doesn't submit the form as expected, it's easy to notice and fix by adding the type attribute. It's not always so intuitive the other way around.
  • Rather than assigning the component to a variable like in the earlier example, I wrapped each in a new component. This is to avoid issues with "unsupported html attribute" errors in the console logs that would occur with passing props like target to the button. This approach also keeps Typescript happy. But it may have performance implications that I haven't found yet.
  • At first I thought it would be ideal if button and link props would be mutually exclusive because it wouldn't be technically valid to have a target without an href. But since I'm using the href to determine which component to render, it can't be excluded from the button props. This also means that any event handlers will have { target: HTMLAnchorElement | HTMLButtonElement } because Typescript merges the two, but I've come to think this approach is the most honest way to go. You could use another prop instead of href, such as (RawButtonProps & { as?: 'button' }) | (RawLinkProps & { as: 'link' }) to get the exclusions working, but like with function overload signatures, it becomes susceptible to weird edge cases and the types become more difficult to work with. Overall, I think I can rely on developers to know that if they pass a target without an href then it will be ignored, and this is far preferable to weird edge cases like passing { ...rest } props where the Typescript doesn't see the href or as prop and defaults to using button props but ends up being a link and passing the wrong event type.

Bouncing Baby Buttons

There's not much more to say at this point.

Now that we have our <Action> component, defining a button is simply a matter of making a component that looks like a button.

There are alot of ways to approach this and there are alot of styles out there to mirror.

For this site, I'm using Tailwind and CVA so my button components simply look like this:

1import { cva, VariantProps } from 'class-variance-authority'
2import { twMerge } from 'tailwind-merge'
3import React from 'react'
4import { Action } from '../Action/Action'
5import { ActionProps } from '../Action/ActionProps'
6
7export const buttonVariants = cva(
8  'inline-flex items-center font-bold no-underline justify-center whitespace-nowrap rounded transition-all duration-200 disabled:opacity-50',
9  {
10    variants: {
11      appearance: {
12        solid: 'bg-red-500 text-white hover:bg-red-500/80',
13        glow: 'bg-red-500 text-white shadow-lg shadow-red-500/50 hover:bg-red-600',
14      },
15      size: {
16        sm: 'h-8 px-3',
17        md: 'h-10 px-6',
18        lg: 'h-12 px-9',
19      },
20    },
21    defaultVariants: {
22      appearance: 'solid',
23      size: 'md',
24    },
25  },
26)
27
28export type ButtonProps = ActionProps & VariantProps<typeof buttonVariants>
29
30export function Button(props: ButtonProps) {
31  const { appearance, size, className, ...restProps } = props
32
33  return (
34    <Action
35      {...restProps}
36      className={twMerge(
37        buttonVariants({ appearance: appearance, size, className }),
38      )}
39    />
40  )
41}
42

If the Action component is functionality without form then the Button component is all form at this point. The ActionProps and Action component do most of the heavy lifting while the Button component itself just passes on the className prop to specify the styles to use.

And of course there are lots of ways to compose these. Supporting an icon button could be a new variant or could be its own IconButton component.

With this abstraction, my recommendation is to name things based on what they look like since that's how designers, your product team, and your users will refer to them. Now you can go forth and create all manner of button and link components without worrying about the underlying functionality.