Search code examples
reactjsstyled-componentsemotion

How to create dynamic styled component?


What I'm trying to achieve is something like this:

import styled from 'react-emotion'

const StyledComponent = styled(({tag}) => tag)`
    // some css styles
`

And use it like:

<StyledComponent tag=div"/>
<StyledComponent tag="p"/>
<StyledComponent tag="ul"/>
// etc

My expectation was that it should generate HTML as follows:

<div class="some-class"></div>
<p class="some-class"></p>
<ul class="some-class"></ul>

Actual output:

div
p
ul

My question is, can this be achieved or am I missing anything?


Solution

  • Seems like I have figured out a solution to my problem. Sharing my answer for those who may run into the same problem.

    I changed StyledComponent declaration to following:

    import styled from 'react-emotion'
    
    const StyledComponent = styled(({tag, children, ...props}) => React.createElement(tag, props, children))`
        // some css styles
    `
    

    This is working as expected.

    If anyone has the better answers please do post. Thank you