You can use component above to create a beautiful button. Nothing wrong with that component. Until someday you want create a link with same style with the <button /> component.
Maybe you will use this approach.
<ahref="..."><Button>To next page</Button></a>
Of course it should work, but the code doesn't look so fluent. Meaning to say. If you use HTML, you can write it like this:
// We assume <a /> using same styling with <button /><ahref="...">To next page</a>
Based on the problem above, polymorphic component offers you a solution like this:
<Buttonas="a"href="...">To next page</a>
See? You don't need to wrap the <Button /> component using <a /> because it's automatically convert the the returned element to <a />.
Building The Component
Now let's build the component and it's very easy. All you need is only React createElement API.
We also changed the JSX to createElement API to give us more control when creating the component.
If you not familiar. Actually when you use JSX, under the hood it will transform your code to createElement.
By using the createElement API, we are able to conditionally create a component. That's why when you are not passing a value into the as props, the default element of <Button /> component is <buttton />.
And that's it... You have created a polymorphic component.
Conclusion
Polymorphic component may sounds very fancy and difficult, but it's not.
The term of polymorphic is a general term in computer science. You can read about it here.
One of my favorite backend framework, Laravel, is also has a feature called polymorphic relationships which use this term.
In React world, polymorphic component refers to an ability of a component that can returns different element with a same style without removing the default functionality.
It's really help when you facing a problem where you want to use other HTML with a same style.
I hope it gives you something. Thanks for reading :)