polymorphic-react-component
polymorphic-react-component copied to clipboard
Q: How to limit the Element Type
Is there a way we can limit the element type to for eg: Button
and a
?
Been trying to use this helper but I want to narrow it down in some scenarios like <Button as="a">
while disallowing <Button as="form>
or any other element other than button | a
.
Haven't been able to figure out how to do it yet. Any pointers would be greatly appreciated!
That's an interesting use case.
@ Misael Burboa (a Discord user) had posted this solution when they needed to do the same:
The crux is in the HtmlTagsAllowed
type alias.
I still need to test this, but in the latest version of TS, you might be able to do this via instantiation expressions as follows: Typescript playground
I still need to test this, but in the latest version of TS, you might be able to do this via instantiation expressions as follows: Typescript playground
I tried this solution and it comes close, but you end up losing html attributes that aren't shared among all the elements (aka href on an anchor). I've created an example here
The example you posted from Discord does seem to work in an example env, but I can't seem to get it actually limit the as prop locally (may be something else I'm missing, going to keep testing and will report back). Hopefully this helps others experiment with their own use case. Working example