24
loading...
This website collects cookies to deliver better user experience
Button
component that we want to render as an HTML link. If Button is a polymorphic component, we can write it like this:import Button from './Button'
function App() {
return (
<Button as="a" href="https://open.spotify.com">
)
}
export default App
a
tag and it also accepts href
attribute.const Button = ({ as, children, ...props }: any) => {
const Component = as || "button";
return <Component {...props}>{children}</Component>;
};
export default Button;
any
.as
prop or if it's not provided, use the button
tag as fallback.const Component = as || "button";
import Button from './Button'
function App(){
return (
<Button href="https://open.spotify.com">
)
}
export default App
href
prop, which belongs to a
tag, without setting the as
prop to a
.import { ComponentPropsWithoutRef, ElementType, ReactNode } from "react";
type ButtonProps<T extends ElementType> = {
as?: T;
children: ReactNode;
};
const Button = <T extends ElementType = "button">({
as,
children,
...props
}: ButtonProps<T> & ComponentPropsWithoutRef<T>) => {
const Component = as || "button";
return <Component {...props}>{children}</Component>;
};
export default Button;
const Button = <T extends ElementType = "button">
ElementType
is a type from React. We set our parameter T to ElementType to ensure our button only accepts HTML tags and other React component types.Property 'href' does not exist on type 'IntrinsicAttributes & MyButtonProps<"button">
href
property because it doesn’t render itself as a link. If we add as="a"
, the error goes away.