Styled-jsx: How to extend existing Component styles

Created on 16 Jun 2017  路  6Comments  路  Source: vercel/styled-jsx

I try to extend Component A style, but the following code doesn't work. What is the best way to extend styles using styled-jsx?

const A = () => <div>Hello
    <style jsx>{`div {color: red}`}</style>
</div>

const B = () => <A>
    <style jsx>{`
        div {background-color: blue;}
    `}</style>
</A>
// doesn't work, no background-color ejected. 

Most helpful comment

@ron-liu I just found this, multiple ways to style child component:
https://github.com/zeit/styled-jsx#global-selectors
https://github.com/zeit/styled-jsx#dynamic-styles

All 6 comments

It's not recommended but you could use "global styles".

or make it a property of A:

const A = ({bgColor}) => <div>Hello
    <style jsx>{`div {background-color: ${bgColor || 'inherit'}}`}</style>
</div>

or a more meaningful prop of A:

const A = ({isHighlight}) => <div>Hello
    <style jsx>{`div {background-color: ${isHighlight ? 'blue' : 'inherit'}}`}</style>
</div>

or use plain old react inline style:

const A = ({isHighlight}) => (
    <div style={backgroundColor: isHighlight ? 'blue' : 'inherit'}>
        Hello
    </div>
)

@amio you can't use props in styles.. yet

Oops, any details about why?

Because all the instances of a component share the same styles. If you update the styles based on props changes that happened on a single component will affect all of them which is not what you want :)

@ron-liu I just found this, multiple ways to style child component:
https://github.com/zeit/styled-jsx#global-selectors
https://github.com/zeit/styled-jsx#dynamic-styles

You cannot extend components but you could pass some styles/className. See https://github.com/zeit/styled-jsx#styling-third-parties--child-components-from-the-parent

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timsuchanek picture timsuchanek  路  29Comments

jacobmischka picture jacobmischka  路  28Comments

jacobmischka picture jacobmischka  路  23Comments

rauchg picture rauchg  路  17Comments

richtera picture richtera  路  31Comments