styled-jsx: Can't target root with a dynamic tag name

You can’t target a root element with a dynamic tag name, using className:

export default ({children, level = 2}) => {
  const Heading = `h${level}`
  return (
    <Heading className='root'>
      {children}
      <style jsx>{`
        .root {
          color: red;
        }
      `}</style>
    </Heading>
  )
}

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 9
  • Comments: 31 (12 by maintainers)

Most upvoted comments

@arsen that’s on my radar, probably the next most important feature to add!

fixed in #462 will ship with styled-jsx v3

@simonsmith jsx-123456 is also applied to the outer div (.parent).

To style the Link you could temporarily use :global() until we find a better mousetrap:

<div>
   <Link className="my-link">something</Link>
   <style jsx>{`div > :global(.my-link) { color: red }`}</style>
</div>

Any progress on this? 😃

@iamawebgeek this should work

class Button extends React.Component {
  render() {
    return (
      <button className={`button ${this.props.className}`}>
        <style jsx>{`.button { color: white; }`}</style>
        {this.props.children}
      </button>
    )
  }
}

class CoolButton extends React.Component {
  render() {
    const scoped = resolveScopedStyles(
      <scope>
        <style jsx>{`.cool-button { border: 1px solid #808080; }`}</style>
      </scope>
    );

    const classNames = [
      scoped.className,
      'cool-button',
      this.props.className,
    ];

    return (
      <React.Fragment>
        <Button className={classNames.join(' ')}>
          {this.props.children}
        </Button>
        {scoped.styles}
      </React.Fragment>
    )
  }
}

@giuseppeg Yes I could. Some pointers on where to start would be apprichiated 😃

I think that it makes sense to automatically scope (add the className) in the case reported by the OP. In any other case we should scope only when the user adds a prop like styled-jsx otherwise people can use css.resolve i.e. prefer explicitness over magic

When the styles are static it is better to define then outside of the render method otherwise they are treated as dynamic.