Styled Component dynamic tag name

Viewed 11840

I want to make a dynamic component. (the dynamic TAG will be a styled component -> emotion)

const Dynamic = ({ tag: Tag, children, ...rest }) =>
   <Tag {...rest}>
      { children }
   </Tag>

The component will be a styled component like:

const Column = styled(div)({ color: 'red' })
const Row = styled(span)({ color: 'yellow' })

This looks all nice, and working properly, BUUUUUT:

When I try use a DynamicComponent inside another DynamicComponent:

<DynamicComponent tag={Row}>
   {
      mapOver.map(item=>
         <DynamicComponent tag={Column}/>
      )
   }
</DynamicComponent>

then for some reason the Dynamic children will use the Dynamic Parent's style.

Is there anything I missing?

P.S.:

If instead of using dynamic styles, I do something like this:

<Row>
   <Column/>
</Row>

then the styles, classNames, styled tags, are applied properly.

To make it a little more clear:

enter image description here

As you can see the DynamicComponent's will use the parent's styles, classNames, styled tags... (NOT THE BEHAVIOUR I WOULD EXPECT)

2 Answers

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/styled-components@4.4.1/dist/styled-components.min.js"></script>

Reference:

There is a misunderstanding in the usage of styled-components as a tag is intended as HTML tag (input, div and so on). The best way is to define a StyledRow and a StyledColumn separately and use them with appropriate names. This will help also to make your code more readable.

Related