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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With