javascript / intermediate
Snippet
Polymorphic Components with the 'as' Prop
Polymorphic components can render as different HTML elements or even other React components while maintaining consistent styles or logic. The 'as' prop allows the consumer to decide the semantic tag of the component.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const Box = ({ as: Component = 'div', children, ...props }) => {return (<Component {...props}>{children}</Component>);};// Usage examples:// <Box as="button" onClick={doSomething}>Click Me</Box>// <Box as="section" className="hero">Content</Box>
react
Breakdown
1
as: Component = 'div'
Renames the 'as' prop to a capitalized variable so React recognizes it as a component/element.
2
<Component {...props}>
Renders the dynamic component and spreads all remaining props like className or event handlers.