Facyo Kouch
Facyo Kouch

Reputation: 787

Dynamic styled component tag based on prop

I'm trying to create a dynamic tag with styled components. The tag is received via props.

This is the code example:

import * as React from 'react';
import styled from 'styled-components';

type ContainerProps = {
    children: React.ReactNode,
    type?: 'section' | 'div' | 'article',
}

const Container = styled.div`
  color: ${props => props.theme.primaryColor};
`;

const Icon = styled.div<ContainerProps>`
    background-color: red;
`;

const container: React.FunctionComponent<ContainerProps['children']> = ({ children, type = 'section' }: ContainerProps) => {
    return (
        <Container>
            <{ children }
        </Container>
    );
};

export default container;

I'm trying to achieve that the <Container> tag (which is a div now) is a dynamic prop based on the prop.type.

Upvotes: 2

Views: 4203

Answers (1)

Thomas Hennes
Thomas Hennes

Reputation: 9939

You can use the "as" polymorphic prop, like this:

import * as React from 'react';
import styled from 'styled-components';

type ContainerProps = {
    children: React.ReactNode,
    type?: 'section' | 'div' | 'article',
}

const Container = styled.div`
  color: ${props => props.theme.primaryColor};
`;

const Icon = styled.div<ContainerProps>`
    background-color: red;
`;

const container: React.FunctionComponent<ContainerProps['children']> = ({ children, type = 'section' }: ContainerProps) => {
    return (
        <Container as={type}>
            { children }
        </Container>
    );
};

export default container;

See this simple codesandbox I put together based on your code

Upvotes: 8

Related Questions