Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending component props to default html button props correctly

I am working on a button component that has variant prop to determine it's color. Here is simplified version

interface Props extends React.HTMLProps<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {
  console.log(variant);

  return (
    <button
      type="button"
      {...props}
    />
  );
}

I am getting typescript error under my type that says:

(JSX attribute) ButtonHTMLAttributes.type?: "button" | "submit" | "reset" | undefined Type 'string' is not assignable to type '"button" | "submit" | "reset" | undefined'.ts(2322) index.d.ts(1872, 9): The expected type comes from property 'type' which is declared here on type 'DetailedHTMLProps, HTMLButtonElement>'

So I am not sure if I am extending to button props correctly? Perhaps there is another way?

like image 569
Ilja Avatar asked Nov 26 '19 10:11

Ilja


1 Answers

Codesandbox Live Preview

what you're probably looking for is React.HTMLAttributes<HTMLButtonElement>

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props extends React.HTMLAttributes<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {

  return (
    <button
      type="button"
      {...props}
    />
  );
}

const rootElement = document.getElementById("root");
render(<Button variant='green' />, rootElement);

Update

to being more accurate we can use React.ButtonHTMLAttributes<HTMLButtonElement>

import * as React from "react";
import { render } from "react-dom";

import "./styles.css";

interface Props extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant: 'yellow' | 'green';
}

function Button({ variant, ...props }: Props) {

  return (
    <button
      type="button"
      {...props}
    />
  );
}

const rootElement = document.getElementById("root");
render(<Button variant='green' />, rootElement);
like image 145
Secret Keeper Avatar answered Sep 27 '22 19:09

Secret Keeper