Polymorphic Components

One of the first concepts you will encounter is the creation of reusable components. These components allow you to write code once and reuse it many times. The basic building blocks for classic reusable components are props (external data) and state (internal data). You pass props to your component, use them internally, and render a React element.


What if it could dynamically determine the type of element it renders based on a prop? Enter Polymorphic Components! A polymorphic component is a component that can be rendered with different container elements or nodes. Rather than always rendering the same element, such as a <div>, a polymorphic component enables users to choose the element it ultimately renders.


Polymorphic components have a default element that is used when the component prop is not provided. For instance, the default element for the Button component is a button, but it can be changed to an 'a' or any other element or component.


Let's create custom Polymorphic Component


The CustomPolymorphicComponent has an 'as' prop that enables users to specify the type of the rendered element. By default, it is set to 'div'.


The 'Element' variable is destructured from the props and used as the type of the rendered element, with a default value.