Polymorphic Components in Chakra UI
Learn about the use of polymorphic components in the open-source Chakra UI library
We'll cover the following...
Introduction
Chakra UI is a simple, modular, and accessible component library that gives us the building blocks we need to build our React applications. It’s easy to use, has dark-theme support, and is accessible by default.
In general, we achieve reusability in React components by using props. So, how does Chakra UI implement polymorphic props? The answer is by exposing an as prop.
The as prop is passed to a component to determine what container element to render to. Here's an example of using the Chakra UI as prop on a Box component:
<Box as='button'>Button</Box>
We can use the as prop to change the element render, just like styled components.
By default, the Box component renders a div. However, by passing as='button', the Box component will now render a button element.
Chakra UI's polymorphic prop
Using the as prop is quite straightforward.
We pass it to the component. In the example above, it was the Box component. It looks like this:
<Box as="button"> Hello </Box>
Next, the component will render a button element.
Now, let's change the as prop to an h1.
<Box as="h1"> Hello </Box>
Now, the Box component renders an h1 element.
That’s a polymorphic component at work!
The same component is rendered to entirely unique elements, all by passing down a single prop.
To fully appreciate this lesson:
-
Take a look at the rendered
Boxcomponent. -
Inspect the rendered UI element.
-
Change the value of the
asprop and inspect the new rendered UI element.
Try it yourself
Below is a code playground with a basic Chakra UI project setup.
Click the “Run” button to view the project.