I am building a library of components and I need some of them to have a customizable tag name. For example, sometimes what looks like a <button>
is actually a <a>
. So I would like to be able to use the button component like so:
<Button onClick={onClick}>Click me!</Button>
<Button as="a" href="/some-url">Click me!</Button>
Ideally, I would like the available props to be inferred based on the "as" prop:
// Throws an error because the default value of "as" is "button",
// which doesn't accept the "href" attribute.
<Button href="/some-url">Click me!<Button>
We might need to pass a custom component as well:
// Doesn't throw an error because RouterLink has a "to" prop
<Button as={RouterLink} to="/">Click me!</Button>
Here's the implementation, without TypeScript:
function Button({ as = "button", children, ...props }) {
return React.createElement(as, props, children);
}
So, how can I implement a "as" prop with TypeScript while passing down the props?
Note: I am basically trying to do what styled-components
does. But we are using CSS modules and SCSS so I can't afford adding styled-components. I am open to simpler alternatives, though.
T extends ComponentType<any>
is matching things that it shouldn't: tsplay.dev/rw2j1w You could perhaps copy some type declarations from the styled-components package.