Search code examples
javascriptcssreactjsstyled-componentsemotion

Styled Component dynamic tag name


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)


Solution

  • 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.