Styled-jsx: Passing parameters while loading CSS from external file

Created on 25 Oct 2017  路  6Comments  路  Source: vercel/styled-jsx

I'm trying to load CSS from separate file and also want to pass some parameters to make it dynamic but I'm getting this Error: SyntaxError: Expected a template literal or String literal as the child of the JSX Style tag (eg: <style jsx>{some css}</style>), but got CallExpression

Component file

...
import styles from './style'
...

render() {
    const { children, theme } = this.props

    return(
        <div>
            <button>{ children }</button>

            <style jsx>{ styles(theme) }</style>
        </div>
    )
}
...

CSS File

import css from 'styled-jsx/css'

export default (theme) => (
    css`
        button {
            color: white;
            background-color: ${ theme === 'primary' ? 'red' : 'blue' };
        }
    `
)

Most helpful comment

馃様 Abstracting away the entire CSS code provides much better code structuring and readability. Currently, since most of the CSS is dynamic (based on props) I'll have to clutter the Component code instead. Any chance of this to be implemented in future?

All 6 comments

External styles dont work with dynamic styles. You may want to move the dynamic parts to inline style tags in your components

馃様 Abstracting away the entire CSS code provides much better code structuring and readability. Currently, since most of the CSS is dynamic (based on props) I'll have to clutter the Component code instead. Any chance of this to be implemented in future?

CC: @rauchg @nkzawa

I'd like to see this as well. I agree with @atulmy here and prefer to keep components clean.

This is pretty old, but this is what I did to get by this error:

Component

import { style } from './style'
...

render() {
    const { children, theme } = this.props
    buttonStyle = style(theme)
    return(
        <div>
            <button>{ children }</button>
            <style jsx>{ buttonStyle }</style>
        </div>
    )
}

style.js

import css from 'styled-jsx/css'

export function style(theme) {
    return css`
        button{
            color: white;
            background-color: ${theme === 'primary' ? 'red' : 'white'};
        }
    `
}

This is pretty old, but this is what I did to get by this error:

Component

import { style } from './style'
...

render() {
    const { children, theme } = this.props
    buttonStyle = style(theme)
    return(
        <div>
            <button>{ children }</button>
            <style jsx>{ buttonStyle }</style>
        </div>
    )
}

style.js

import css from 'styled-jsx/css'

export function style(theme) {
    return css`
        button{
            color: white;
            background-color: ${theme === 'primary' ? 'red' : 'white'};
        }
    `
}

This worked for me

Was this page helpful?
0 / 5 - 0 ratings