Styled Component dynamic tag name

Below example creating a dynamic tag name for a styled-component:

// All headings use the same styled-component "Heading" function
const StyledHeading = styled.div`
    font-size: ${({level}) => 4/level }em; // <- dynamic font size
    font-weight: 300;
    margin: 0;
`

// the trick here is the "as={...}" to create dynamic tag name
const Heading = ({level = 1, children}) => 
    <StyledHeading as={`h${level}`} level={level}>
        {children}
    </StyledHeading>


ReactDOM.render([
    <Heading>Hello, world!</Heading>,
    <Heading level={2}>Title 2</Heading>,
    <Heading level={3}>Title 3</Heading>
  ] ,document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/styled-components.min.js"></script>

Reference:

  • "as" prop documentation