The 'as' Prop for Polymorphic Components
What you'll learn: How to use styled-components' as prop to swap the underlying HTML element while preserving all your styles.
The Problem
You've styled a component to look like a button, but sometimes you need it to be an actual <a> tag for navigation, or maybe a <div> for non-interactive cases. Without the as prop, you'd have to create separate styled components for each element type—tedious and error-prone.
How the as Prop Works
The as prop lets you change the rendered element of a styled component on the fly, without losing any of the styles you defined. Think of it like swapping the chassis of a car while keeping the paint job, interior, and all the features intact.
import styled from 'styled-components';
const Button = styled.button`
padding: 12px 24px;
background: blue;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
`;
function App() {
return (
<>
{/* Renders as <button> */}
<Button onClick={() => alert('Clicked!')}>
Click Me
</Button>
{/* Same styles, but renders as <a> */}
<Button as="a" href="/home">
Go Home
</Button>
{/* Same styles, but renders as <div> */}
<Button as="div">
Non-interactive
</Button>
</>
);
}
All three elements look identical, but the underlying HTML is different. You get semantic correctness (links are <a> tags, buttons are <button> tags) without duplicating style code.
Why This Matters
Polymorphic components give you maximum flexibility with minimal code. One styled definition serves many use cases. You're not creating StyledButton, StyledLink, and StyledDiv—you're reusing intelligently.
Key Takeaway: The as prop transforms styled-components into polymorphic components, letting you change the underlying element while keeping all styles intact—semantic HTML without style duplication.