Styled-components: v4 beta constructive feedback

Created on 5 Sep 2018  ·  148Comments  ·  Source: styled-components/styled-components

Please provide as much detail as possible when commenting here so we can help! A huge amount of time and thought has been put into the API changes. We know it won't be a "flip a switch" situation, but the ergonomics of the library going forward should be markedly better and more flexible.

Most helpful comment

@JeroenReumkens v4 TS typings are now out: https://www.npmjs.com/package/@types/styled-components

All 148 comments

When doing server-side rendering, webpack resolve.module and resolve.alias don't work as expected. And while these lines only check for a browser environment, there's some broken behavior in SSR.

Because of the new use of React.createContext it's imperative that the same instance of styled-components is used, otherwise theming will not work. We're having an issue where resolve.module and resolve.alias isn't helping (SSR) but we still have hoisted and non-hoisted styled-component packages in our monorepo, causing SSR to fail due to an empty theme.

I've spent a bit trying to come up with a solution for this, but so far I haven't been able to get around Node's resolution algorithm to get it to resolve to the right instance.

@migueloller Do you use yarn by any chance? They have a nifty package.json field called "resolutions" you can use to force-dedupe styled-components at the package manager level:

{
  "resolutions": {
    "styled-components": "beta"
  }
}

We do! Unfortunately it’s not an issue of different versions. We have the beta version in the hoisted node_modules as well as the no-hoisted one. The issue is because of how the modules are resolved.

We have a component library that imports from the hoisted package and we have application code that imports from the no-hoisted package. The application also imports from the component library. When webpack works as expected (i.e., front end build), it will properly use resolve.alias to always pick the no-hoisted dependency. Unfortunately, for SSR that’s not the case, causing the instance of styles-components to be different.

@migueloller since this is a dedup issue that's more related to tooling, there's not much we can do 😅

There's an alternative solution here: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021

But in your case it sounds like you might want to use babel-plugin-module-alias or module-alias for node

Thank you and congratulations for the awesome work, guys.

I have an issue here.

I was trying to test the behavior of the as prop (I wanted to know whether it conflicts with existing as props in custom components), but it's throwing this error:

Could not find module in path: 'styled-components' relative to '/index.js'

https://codesandbox.io/s/xv6rrlk3oo

I'm not sure if that's a bug on CodeSandbox, but it doesn't happen on v3.4.5.

@diegohaz I think it just didn't redownload the dependency for whatever reason? When I clicked the little "reload" symbol next to the dep it worked 🤷‍♂️

https://codesandbox.io/s/qv3x6x56xq

@probablyup I guess that worked because you just reverted it to v3.4.5 XD

LOL oy. Looking.

@probablyup and @kitten,

After giving this some thought and sleep, I've found a solution. When using Lerna, or just symlinks, the solution is to run Node with the --preserve-symlinks flag.

What this will do is that is a package is required and the resolution somehow follows a symlink, it will come back up that symlink when looking for node_modules.

In our case, this is exactly what we needed since our folder structure pretty much looks like the one shown in the Node docs for this CLI flag.

This seems like a common thing for people using monorepos and Lerna. The same way you guys added the caveat for multiple instances and how it can be fixed in webpack, should we add something to the website explaining this solution for Node?

@diegohaz might be this https://github.com/CompuIves/codesandbox-client/issues/645 - waiting to see if the code owner replies. We removed "jsnext:main" in v4 since "module" is mainstream now, wondering if that broke something.

@migueloller Yeah I think that makes sense for sure!

@Grmiade yes it's noted in the migration instructions under #6

We moved to DefinitelyTyped. But also the types will need to be added by someone for createGlobalStyle, etc.

Hum, weird, my comment has disappeared 🤔
Oups my bad 🙈I didn't see that, thanks.
It is a pity to do this I think, it's more intuitive when typings is provided by the repo itself ;)

@Grmiade see https://github.com/styled-components/styled-components/issues/1778 for more context on that decision

@migueloller yes, if you're using monorepos it should become easy as pie :) I'd also recommend Yarn Workspaces if you're not using that already which eliminates this problem altogether given that you keep the styled-components version in sync across packages

@kitten, I'm using Yarn Workspaces. The issue wasn't a mismatch in versions but instead a mismatch in instances. There were 2 [email protected], one hoisted in the root node_modules and one that wasn't. Since v4 is now using React.createContext the consumer didn't match the provider even though the versions were the same. The only way to fix this is to use --preserve-symlinks.

I've got another issue going on. Maybe this one's something that you guys can figure out quickly.

For some reason, our styles get mangled in production. I did go in-depth into the built styled-components source and was able to track the bug down to DISABLE_SPEEDY being equal to false. When doing SSR, styles come fine from the server. Then, as soon as the client bundle loads, GlobalStyle.prototype.removeStyles removes non-global styles, causing our styles to get mangled. If it helps, we're using two global styled components and GlobalStyle.prototype.removeStyles seems to be called twice, each call mangling more styles.

When DISABLE_SPEEDY is true, this doesn't seem to be an issue, which is why in development the problem isn't there. Also, I'm not sure if this is intended behavior or if it's a bug. I'm sorry I can't get a repro but the codebase where this is happening in is pretty complex and the styles that are getting removed don't seem to be deterministic. Hopefully this is enough information to go on.

cc: @imbhargav5

UPDATE: Can confirm that removing our global styled components from the client bundle "fixes" the bug, which means that global styled components are indeed removing styles that they shouldn't be.

UPDATE 2: Can also confirm that GlobalStyle.prototype.removeStyles is being called for each global styled component on each render.

@migueloller This might help https://github.com/styled-components/styled-components/pull/1976

I published it under styled-components@dev, could you give it a shot?

@probablyup, that fixed it! Really appreciate the prompt response 😄

Great. Assuming that passes review I’ll cut a patch for it tomorrow
On Wed, Sep 5, 2018 at 8:31 PM Miguel Oller notifications@github.com
wrote:

@probablyup https://github.com/probablyup, that fixed it! Really
appreciate the prompt response 😄


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-418934282,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1rJ-ixaUiBPijDWPaWYjzCL6ODKdks5uYHsIgaJpZM4WZ4nX
.

Styled components no longer appears as an installed package according to ‘npm ls’. Not sure what this means, or if it will cause any real issues. Just something I noticed while debugging Rebass after the update.

https://github.com/styled-components/styled-components/releases/tag/v4.0.0-beta.1 is out which includes the fixes noted above in styled-components@dev

Get it via npm update styled-components@beta

The addition of the as prop will cause some problems for the https://github.com/reakit/reakit project.

I've created https://github.com/reakit/reakit/issues/226 to explain it more thoroughly and offer some proposed solutions for how that project should proceed.

Feedback on that issue would be welcome.

Hello everyone, congrats on shipping the beta.

The abstractions that have been introduced in v4, make the Enzyme snapshots pretty noisey.

Similar issue with the React DevTools extension:

screen shot 2018-09-08 at 11 55 38 am

Is there any plan to address this, or should we implement a "workaround" in jest-styled-components?

Thank you very much!

Given the current set of APIs to work with, there’s no way we could address
it in the library unfortunately.
On Sat, Sep 8, 2018 at 6:01 AM Michele Bertoli notifications@github.com
wrote:

Hello everyone, congrats on shipping the beta.

The abstractions that have been introduced in v4, make the Enzyme
snapshots pretty noise
https://gist.github.com/MicheleBertoli/ea08aa9979e873666f3e3276c2f9c2ea.

Similar issue with the React DevTools extension:

[image: screen shot 2018-09-08 at 11 55 38 am]
https://user-images.githubusercontent.com/1308971/45253396-44f4ed00-b35e-11e8-96c2-2e59e8353a0b.png

Is there any plan to address this, or should we implement a "workaround"
in jest-styled-components?

Thank you very much!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419633251,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1lEPsD_xNwUOX4FrfoPq1TvOT8VTks5uY6NrgaJpZM4WZ4nX
.

Revert ES6 as default distribution?

I've tried to run my jest tests after upgrading to styled-components v4, and I started getting the typical:

  unexpected token `import`

I have to configure jest to add babel transform to node_modules/styled-components and this is the only module where I'm having to do this. I can't imagine if other libraries start doing this, where I get these unpredictable failures and have to figure out which library I have to transform and which ones I don't.

I understand that es6 helps with tree shaking but I feel it should not be the default distribution. In styled-components v3 you guys are doing exactly as I would expect: https://github.com/styled-components/styled-components/blob/master/package.json#L6.

Are you using one of the dev beta versions by any chance? I pushed a non
functional version to the dev tag before. Make sure you’re using the beta tag
to install.
On Sat, Sep 8, 2018 at 10:04 PM Alan Souza notifications@github.com wrote:

Revert ES6 as default distribution?

I've tried to run my jest tests after upgrading to styled-components v4,
and I started getting the typical:

unexpected token import

I have to configure jest to add babel transform to
node_modules/styled-components and this is the only module where I'm
having to do this. I can't imagine if other libraries start doing this,
where I get these unpredictable failures and have to figure out which
library I have to transform and which ones I don't.

I understand that es6 helps with tree shaking but I feel it should not be
the default distribution. In styled-components v3 you guys are doing
exactly as I would expect:
https://github.com/styled-components/styled-components/blob/master/package.json#L6
.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419687299,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1llkk7hx59i8ykapbWI6LJEtmfSeks5uZIVIgaJpZM4WZ4nX
.

I'm using 4.0.0-beta.1-2 and here is the package.json config:

"main": "index.esm.js",
  "module": "index.esm.js",

Yeah that’s a dev release I was testing something with. You can tell by the
-2 at the end. Make sure you’re using beta.1
On Sat, Sep 8, 2018 at 10:30 PM Alan Souza notifications@github.com wrote:

I'm using 4.0.0-beta.1-2 and here is the package.json config:

"main": "index.esm.js",
"module": "index.esm.js",


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419688189,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1qfGAXf5NPm6KTpYMrxJa6l4UizNks5uZIs9gaJpZM4WZ4nX
.

gotcha. glad to hear that you are doing styled-component stuff now @probablyup

Oh yeah I’ve been cranking on this for a while 😁

Hi there. I'm having an issue with global styles being re-rendered multiple times (as warning says):

The global style component sc-global-1057310270 was composed and rendered multiple times in your React component tree. Only the last-rendered copy will have its styles remain in .

This is happening on every page navigation (no SSR involved, as I know).
Environment: [email protected], [email protected].
Here is a repo to reproduce
And here is how global styles are used

Not sure if it's only related to support from Gatsby's side 🤷‍♂️
Gatsby issue for sc v4 support: https://github.com/gatsbyjs/gatsby/issues/7897

@amankkg can you try styled-components@dev and let me know if that takes care of the warning?

@styled-components/typers hey folks - the API is solidified now for v4. If you could start updating the definitions for TS and Flow that'd be appreciated!

Hello,

I am using 4.0.0-beta.2-0. I am getting issues when testing with Jest and Enzyme. The issue seems to be occurring when extending another styled component.

So the code:

const CompA = styled(CompB)`
  height: 100%;
  width: 100%;
`;

// failed test
 it('should have a className attribute', () => {
    const renderedComponent = shallow(<CompA />);
    expect(renderedComponent.prop('className')).toBeDefined();
  });

Tests seem to fail and when logging out the renderedComponent I get:

<BaseStyledComponent forwardedClass={{...}} forwardedRef={{...}} />

Getting an error in every location I import styled-components:
Module not found: Error: Can't resolve 'styled-components/no-tags'

Sure enough, checking node_modules/styled-components/no-tags/dist, the folder is empty.

Edit: Error present on 4.0.0-beta.2-0 and 4.0.0-beta.1

Update your version of the babel plugin please
On Mon, Sep 10, 2018 at 10:47 AM gi-alec notifications@github.com wrote:

Getting an error in every location I import styled-components:
Module not found: Error: Can't resolve 'styled-components/no-tags'

Sure enough, checking node_modules/styled-components/no-tags/dist, the
folder is empty.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419961024,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1rH3CHxgapbU4aDMFp6iTLaxGmORks5uZol7gaJpZM4WZ4nX
.

@probablyup, I am using "babel-plugin-styled-components": "^0.0.3-0" & "styled-components": "^4.0.0-beta.2-0",

Still getting:

 Expected value to equal:
      "section"
    Received:
      [Function BaseStyledComponent]

I am also getting a number of other issues:

// Fails
expect(renderedComponent.prop('className')).toBeDefined();
// Fails
 const renderedComponent = render(<CenteredSection attribute="test" />);
 expect(renderedComponent.props('attribute')).toBeUndefined();

Uh that’s a really really old version of the babel plugin
On Mon, Sep 10, 2018 at 12:12 PM TheboyWhoCriedWoolf <
[email protected]> wrote:

@probablyup https://github.com/probablyup, I am using "babel-plugin-styled-components":
"^0.0.3-0" & "styled-components": "^4.0.0-beta.2-0",

Still getting:

Expected value to equal:
"section"
Received:
[Function BaseStyledComponent]


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419989314,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1t8JeBBVPonKAAeCacQD94eOSUMWks5uZp2IgaJpZM4WZ4nX
.

And you’re also using a prerelease version of the library. Please follow
the installation instructions as written
On Mon, Sep 10, 2018 at 12:15 PM Evan Jacobs probablyup@gmail.com wrote:

Uh that’s a really really old version of the babel plugin
On Mon, Sep 10, 2018 at 12:12 PM TheboyWhoCriedWoolf <
[email protected]> wrote:

@probablyup https://github.com/probablyup, I am using "babel-plugin-styled-components":
"^0.0.3-0" & "styled-components": "^4.0.0-beta.2-0",

Still getting:

Expected value to equal:
"section"
Received:
[Function BaseStyledComponent]


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-419989314,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1t8JeBBVPonKAAeCacQD94eOSUMWks5uZp2IgaJpZM4WZ4nX
.

The plugin was incorrectly installed as a dependency, moving it to a devDependency solved the issue. For context, this is a Gatsby project.

@probablyup updated to styled-components@dev (4.0.0-beta.2-0). No dev warnings so far 🎉🎉🎉

Installed both via npm install styled-components@beta babel-plugin-styled-components@beta. I am still getting the same issue.

Now running with:

"styled-components": "^4.0.0-beta.2",
 "babel-plugin-styled-components": "^1.6.4"

All my React dependencies are up to date also.

Is there something else that could be causing the issue?

There is no beta of the babel plugin.

If you can make some sort of reproduction repo we might be able to help, but code snippets like that without any context of your setup aren't actionable.

I created a simple repo to demonstrate the issue: https://github.com/theboyWhoCriedWoolf/styled-v4-test.

Just yarn/npm install then run test:watch. I still seem to be getting issues.

Any help would be much appretiated.

@theboyWhoCriedWoolf ok I see. I don't think shallow rendering is going to work. The reason why is a styled component in v4 is actually like 4 "layers" of components.

ForwardRef(StyledComponent(StylesheetConsumer(ThemeConsumer(Target)))

You'll need to use mount from enzyme and use a testing helper like this until enzyme handles forwardRef better.

I'm experiencing some issues with HMR and the new createGlobalStyle API. The updated style is not always applied, not sure if it's not injecting or has the wrong specificity. I'll come back with a repro when I get some time over. This is using Gatsby v2 FYI

@alexandernanberg a repro would be awesome, thank you

Trying styled-components v4 beta3. Seems it doesn't whitelist props anymore?

v4 https://codesandbox.io/s/z3rrzqlq8l - note the error in the console

v3 https://codesandbox.io/s/149kv1roo4

should I report a bug or did I miss anything?

Also, a new styled component propType is an object, but it was a function before and it breaks prop type checking now. If it's expected behavior maybe should mention it somewhere.

@denisborovikov This is by design, see how the prop filtering works here: https://github.com/emotion-js/emotion/blob/master/next-packages/is-prop-valid/src/props.js#L468

on{X} is an established React pattern for passing events, so we don't filter it in case you want to pass onInput, onClick etc to the element. We can't possibly check every possible combination or the library would be quite bloated and probably unmaintainable, so we make some small compromises here and there where there's precedent.

Also, a new styled component propType is an object, but it was a function before and it breaks prop type checking now. If it's expected behavior maybe should mention it somewhere.

This is the nature of React.forwardRef. The types will probably have to be updated to account for this, but it still acts like a component and is used identically. Frustrating, I know.

@probablyup https://github.com/alexandernanberg/gatsby-starter-default/tree/createGlobalStyle-repro

  1. Set up the project (install deps and so on)
  2. Run yarn develop to start dev server
  3. Go to layout.js and change some of the css properties (eg set the html margin to 44px)
  4. Now change property value again and notice that no changes are applied (sometimes you have to make more than one change for the HMR to stop work)

Not sure if this is a Gatsby or Styled components bug, but this works with the old injectGlobal API

@alexandernanberg I can't reproduce it. Works every time for me and I did about 15 changes, including adding and removing rule blocks.

@probablyup Hmm that's weird... I'm still seeing issues but I might have narrowed it down a bit now – it only seems to affect html or body selectors. Did you try to change the margin value multiple times?

Can try it on another computer as well, if you still are not able to reproduce it.


Gatsby debug info

System:
  OS: macOS High Sierra 10.13.6
  CPU: x64 Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
  Shell: 5.3 - /bin/zsh
Binaries:
  Node: 10.9.0 - ~/.nvm/versions/node/v10.9.0/bin/node
  Yarn: 1.9.4 - /usr/local/bin/yarn
  npm: 6.4.1 - ~/.nvm/versions/node/v10.9.0/bin/npm
Browsers:
  Chrome: 69.0.3497.92
  Firefox: 62.0
  Safari: 11.1.2
npmPackages:
  gatsby: next => 2.0.0-rc.23 
  gatsby-plugin-manifest: next => 2.0.2-rc.1 
  gatsby-plugin-offline: next => 2.0.0-rc.7 
  gatsby-plugin-react-helmet: next => 3.0.0-rc.1 
  gatsby-plugin-styled-components: ^3.0.0-rc.5 => 3.0.0-rc.5 

Yeah a bunch of times

I can reproduce a bug similar to @alexandernanberg 's with next setup:

"gatsby": "^2.0.0-rc.23",
"gatsby-plugin-styled-components": "^3.0.0-rc.5",
"react": "^16.5.1",
"react-dom": "^16.5.1",
"styled-components": "^4.0.0-beta.4",
"babel-plugin-styled-components": "^1.7.1",

Reproduction:

  1. body margin is 0 initially
  2. set margin 20px - applied
  3. set margin 50px - applied
  4. set margin back to 0 - not applied, no errors, HMR worked out as before

HMR logs

[HMR] bundle rebuilding
PATH/node_modules/webpack-hot-middleware/client.js?path=http:/localhost:8000/__webpack_hmr&reload=true&overlay=false:242 [HMR] bundle rebuilt in 102ms
PATH/node_modules/webpack-hot-middleware/process-update.js:39 [HMR] Checking for updates on the server...
PATH/node_modules/webpack-hot-middleware/process-update.js:112 [HMR] Updated modules:
PATH/node_modules/webpack-hot-middleware/process-update.js:114 [HMR] - ./src/global-style.js
[10 times] PATH/node_modules/webpack-hot-middleware/process-update.js:114 [HMR] - undefined
PATH/node_modules/webpack-hot-middleware/process-update.js:119 [HMR] App is up to date.
PATH/node_modules/react-hot-loader/dist/react-hot-loader.development.js:1662 [Violation] 'setTimeout' handler took 132ms
VM563 app.js:96 [Violation] 'setTimeout' handler took 135ms

Changing background color works as expected: none -> purple -> teal -> none - all applied OK.

@amankkg your specific repro steps work thanks, looking into it

@amankkg @alexandernanberg I think I fixed it. Can you try styled-components@experimental and let me know?

@probablyup Yes, it works for me! 🎉

Something else to report... In the past, we had a problem with SSR where styles were sent down in incorrect order, causing style differences between client-side and server-side rendering. This problem had been fixed, but it's now happening again. I'm still not sure of what is causing this, any idea of what it could be?

Currently using v4.0.0-beta.0-1.

Try upgrading to latest beta. There was an SSR fix in 2 or 3.
On Fri, Sep 14, 2018 at 7:40 AM Miguel Oller notifications@github.com
wrote:

Something else to report... In the past, we had a problem with SSR where
styles were sent down in incorrect order, causing style differences between
client-side and server-side rendering. This problem had been fixed, but
it's now happening again. I'm still not sure of what is causing this, any
idea of what it could be?

Currently using v4.0.0-beta.0-1.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-421346189,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1qGv7aLU69JOR_4ajvnVznHZoROZks5ua6PWgaJpZM4WZ4nX
.

@probablyup, on v4.0.0-beta.4 and it doesn't fix the issue.

Ok, you’ll need to provide a repro then.

I'm currently running into an issue using styled-components inside my next.js app. I'm running following versions

    "styled-components": "^4.0.0-beta.4",
    "react-dom": "16.5.0",
    "react": "16.5.0",
    "next": "^6.1.2",

My app is failing to compile and when I try to npm install styled-components/no-tags a window pops up asking for my GitHub credentials 🤔 Not sure if it is related to https://github.com/styled-components/styled-components/pull/1987#event-1834463251

styled-components/no-tags in ./next/pages/_document.js

To install it, you can run: npm install --save styled-components/no-tags
(node:1000) DeprecationWarning: Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead

Can you upgrade your babel plugin please?
On Fri, Sep 14, 2018 at 2:00 PM Mikey Stengel notifications@github.com
wrote:

I'm currently running into an issue using styled-components inside my
next.js app. I'm running following versions

"styled-components": "^4.0.0-beta.4",
"react-dom": "16.5.0",
"react": "16.5.0",
"next": "^6.1.2",

My app is failing to compile and when I try to npm install
styled-components/no-tags a window pops up asking for my GitHub credentials
🤔 Not sure if it is related to #1987 (comment)
https://github.com/styled-components/styled-components/pull/1987#event-1834463251

styled-components/no-tags in ./next/pages/_document.js

To install it, you can run: npm install --save styled-components/no-tags
(node:1000) DeprecationWarning: Module.chunks: Use Module.forEachChunk/mapChunks/getNumberOfChunks/isInChunk/addChunk/removeChunk instead


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-421454158,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1jKs_jjUhacE5uw42CV0nMACSDEXks5ua_zlgaJpZM4WZ4nX
.

Thank you for the fast response. Still have the same issue. I just figured that it has to do with me injecting the GlobalStyle in the Document. If I remove the component it works. I think I can't render the GlobalStyle inside my index.js file because then I can't access my global styles in pages that are not rendered by the / (=index) page.
Below my code

import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet, createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  :root {
    --main-color: #fefefe;
  }
`;

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage((App) => (props) =>
      sheet.collectStyles(<App {...props} />)
    );
    const styleTags = sheet.getStyleElement();

    return { ...page, styleTags };
  }

  render() {
    return (
      <html lang="en">
        <Head>
        </Head>
        <body>
          <GlobalStyle />
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

The “no tags” thing was an experiment that the babel plugin was injecting.
If you’re still seeing that error, the plugin must not be up to date.
On Fri, Sep 14, 2018 at 2:06 PM Mikey Stengel notifications@github.com
wrote:

Still the same issue. I just figured that it has to do with me injecting
the GlobalStyle in the Document. If I remove the component it works. Below
my code

import React from 'react';import Document, { Head, Main, NextScript } from 'next/document';import { ServerStyleSheet, createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle:root { --main-color: #fefefe; };
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
const sheet = new ServerStyleSheet();
const page = renderPage((App) => (props) =>
sheet.collectStyles()
);
const styleTags = sheet.getStyleElement();

return { ...page, styleTags };

}

render() {
return (









);
}
}


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-421455657,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1qgaA_0QAnxhjB7pDdmdkPulO3WQks5ua_5CgaJpZM4WZ4nX
.

Oh. Then it might be caused by me using the smooth-ui style system. It is still on styled-components 3.4.5 along with the old version of the babel plugin. https://github.com/smooth-code/smooth-ui/blob/master/package.json

That should be fine, just run npm or yarn upgrade babel-plugin-styled-components

I have the newest version inside my next.js app but it is being served by a larger adonis.js project using https://github.com/omarkhatibco/adonis-nextjs. Just installed the babel plugin in my adonis app as well but I'm getting the same error.

Are you using yarn? You can force it via the resolutions field until they update.

“resolutions”: {
“babel-plugin-styled-components”: “^1.7.0”
}

That’s weird though. 1.6.4 is when we removed the transpiling for that experiment.

Will try it with yarn now.

@probablyup yep, HMR issue is fixed on beta.4-hmr

Totally fixed it. Thank you 🚀🚀

ISSUE RESOLVED

Not having any luck extending existing Rebass components. It doesn't seem to directly be an issue with Rebass, as I got it working in an isolated repro.
See: https://github.com/rebassjs/rebass/issues/495

I noticed the elements in question show a class name (or 2) in the DOM, but the styles for that class are empty. Here is a gist of the style sheet and element produced for both configurations.

There's something about my project config causing this that I can't seem to put my finger on. I am using Gatsby, so the issue could be on their side as well.

Edit: Even extending a styled.button component isn't working as expected for me. There must be something I'm not understanding. Another gist of the code.

Edit 2: Seems other users are also having issues extending components with Gatsby
https://spectrum.chat/styled-components/?thread=4a2f04dd-b37a-47ea-8633-82f7dc8ba562

Edit 3: Minimal repro here
https://github.com/gi-alec/gatsby-v2-styled-components-v4~~


Issue is resolved using yarn and adding the following to package.json

"resolutions": {
 "hoist-non-react-statics": "3.0.1"
}

I had the same issue in my gatsby project - and it turned out to be related to having an older version of hoist-non-react-statics from the package mdx-js/tag. When I removed that package, extending styled components magically worked again. I manually added [email protected] along with a resolution field in package.json

Credit: Darek Rossman

@gi-alec please use Spectrum or stack overflow for usage questions - we have a ton of tests around extending, so I'm fairly confident it's working

beta 5 is out with the HMR fix - unpublishing the experimental tag

Updated from beta.4-hmr to beta.6 (beta.5 is also broken for me) - navigation breaks global styles without warning (builded version too), hmr does not apply global style changes (as previously, change padding: 10px -> 0 is ignored).

I'm finding that HMR + createGlobalStyle is very difficult... creating weird backflips that have to happen to make things work. It has a very unusual injection flow.

I'll take a look at your project later and see if I can figure it out. Curious why beta.5 didn't work for you since it's pretty similar to the experimental release you were testing.

Yeah, that's weird. Looks like something went wrong starting from this commit. Tried few times with betas 5 and 6. Issue remains.

Cool! Now all is OK. It turns out it was my own bad advice 🤦‍♂️

It made sense at the time... this particular component is very tricky to implement right I've been finding.

Alright folks - things have been pretty stable for the past week other than the createGlobalStyle thing which seems to be resolved.

Assuming this continues, we'll be releasing v4 final on October 1.

In the meantime, if anyone has time to help look at the various typing issues for DefinitelyTyped and flow-typed (cc @styled-components/typers), that would be highly appreciated. And test test test!

@probablyup, that sounds great. Just wanted to let you know that I’m working on getting that repro for the SSR style order issue done. Just haven’t had time 😅

Extending styles using styled(Component) doesn't seem to be working in 4.0.0-beta.7 even at a basic level.

I should also note that extending styles worked as expected when I reverted back to v3.

Relevant package versions

"styled-components": "^4.0.0-beta.7"
"babel-plugin-styled-components": "^1.7.1"
"react": "^16.5.2"
"react-dom": "^16.5.2"

Here's what I did

const RedBox = styled.div`
    background-color: red;
    height: 80px;
    width: 80px;
`

const BlueBox = styled(RedBox)`
    background-color: blue;
    width: 120px;
`

render(
    <div>
        <RedBox />
        <BlueBox />
    </div>
)

I expected styled-components to extend the styles as such:

.Redbox {
    background-color: red;
    height: 80px;
    width: 80px;
}

.BlueBox {
    background-color: blue;
    height: 80px;
    width: 120px;
}

What happened instead was two RedBox components rendering with no indication of of the extended styles being applied. The DOM elements in browser were also identical.

<div>
    <div class="About__RedBox-sc-3vnvld-2 ckHGaJ"></div>
    <div class="About__RedBox-sc-3vnvld-2 ckHGaJ"></div>
</div>

@quinnstonchurchill see this issue: https://github.com/styled-components/styled-components/issues/1972 and specifically this comment for the fix: https://github.com/styled-components/styled-components/issues/1972#issuecomment-419234867

For some reason the hoist-non-react-statics library gets really fubared if there is more than one in the tree at once... we might just have to inline the functionality.

@quinnstonchurchill @gi-alec could you try out styled-components@experimental? It's this PR that inlines the hoisting functionality to hopefully get around the weird package management issues we're seeing.

You'll want to remove the "resolutions" entry when you test.

I tested v.4.0.0-beta.7. Great job! 🎉 😀
I have one issue, when I use React (16.3.0) with Formik and write something like:

import React from 'react';
import { Field } from 'formik';

<StyledInput as={Field} type="text" />

I got an React console warning:

Warning: Invalid value for prop as on tag. Either remove it from the element, or pass a string or number value to keep it in the DOM. For details, see https://fb.me/react-attribute-behavior

Any chance you could put together a quick sandbox? We don't pass the "as" prop down to child components.

Sorry, it works perfect with a component in "as": https://codesandbox.io/s/q3xkz8r7w
Probably we have an issue somewhere else in an app :)

@quinnstonchurchill @gi-alec The hoisting fix is out in v4.0.0-beta.8

@quinnstonchurchill @gi-alec could you try out styled-components@experimental? It's this PR that inlines the hoisting functionality to hopefully get around the weird package management issues we're seeing.

You'll want to remove the "resolutions" entry when you test.

Sorry it took me a bit to get around to this. Just tested, all green here.

Excellent work! 😄 🎆

@probablyup -- the change to use PureComponent for StyledComponent seems to block re-renders of components you use styled() on. for example, I am using v4-beta.8 right now with [email protected] and styled components such as NavLink do not update

Here is a sandbox demonstrating this: https://codesandbox.io/s/m7rqkj6mvj
_You can change StyledHeader to Header in App.js to see the desired behavior_

Here is another sandbox showing that this was working in v3.9.4: https://codesandbox.io/s/m4qmv16r2y

@arempe93 yes that's true, if the props don't change the styled component and underlying component will not rerender. Is there some special behavior the link is meant to do on every render that is independent of the props?

Yes I was about to update the comment 😅

I'm not sure of the underlying implementation (I think they use an old form of context?), but the NavLink is aware of route changes and should update when they happen.

In the sandbox, clicking the links at the top should have them turn red, my way of making this update visible.

Ah ok. They really should upgrade to at least use the create-react-context polyfill or many other libraries will probably break them too. For what it's worth, it was a really simple upgrade when I did it for react-live.

Ah I get it. So if they aren't using the latest 16.3+ context pure components will break their rendering?

If so, I'll go bother them instead. Thanks!

It mostly depends on how they did their legacy context setup. If they used an event emitter in context to handle updates, it would have continued to work fine. But yeah, that polyfill will work for both React 15 and 16 and smooth over this sort of issue 👍

Greetings, I'm not sure if this is the best place to post this, but vscode-styled-components doesn't seem to handle syntax highlighting for createGlobalStyle

Hmmm @TravisBumgarner strange. Seems to be working for me though. Which version are you on? Actually, we should move this issue to vscode-styled-components, since we already have v4 preparations in that repo. Can you open an issue there with a way to reproduce?

I believe it just got merged today, so the update might not have gone out /
gotten to you yet.
On Sat, Sep 22, 2018 at 10:18 AM Bhargav Ponnapalli <
[email protected]> wrote:

Hmmm @TravisBumgarner https://github.com/TravisBumgarner strange. Seems
to be working for me though. Which version are you on? Actually, we should
move this issue to vscode-styled-components, since we already have v4
preparations in that repo. Can you open an issue there with a way to
reproduce?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-423751167,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1qKJjRVc07cz1q-aMWlA3KnvOtO2ks5udlSygaJpZM4WZ4nX
.

I see the update now. Thanks!

Hi! :smiley:

I have two problems after updating styled-components to v4.0.0-beta.8. Here is an example:
https://github.com/azat-io/react-router-dom-demo/blob/master/App.js

1. After updating styled-components my react-router-dom began to work incorrectly. I'm trying to switch to some page -- URL is updating, but not content. If I refresh page -- content is OK. Seems like styled component is blocking updates from <Router> so they cannot reach <Switch>. Everything is ok with styled-components v3.4.9

2. The second problem is warning:

It looks like there are several instances of 'styled-components' initialized in this application. This may cause dynamic styles not rendering properly, errors happening during rehydration process and makes your application bigger without a good reason.

I cannot understand what's wrong with code

You can see both of the above problems in this example:
https://github.com/azat-io/react-router-dom-demo/blob/master/App.js

I will be glad your help :heart:

@azat-io for the second one you probably need to dedupe the library, this comment should help: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021

Not sure about the first one. I believe react-router-dom uses new React context, so it should definitely be receiving context updates. Are you using any other libraries in your stack that are using legacy context?

@azat-io seems to work in my minimal reproduction: https://codesandbox.io/s/nr0k2o9z64 - there's likely another library interfering

@probablyup,

1. Do you think it is react-router-dom problem? It works good only if I remove components which are using styled-components

2. Looks like I have only one styled-components in my project:

image

I don't understand your example on codesandbox. It seems you just removed components which are using styled-components

Ok I see. They just merged React v16 context support a few days ago but haven't released it yet: https://github.com/ReactTraining/react-router/pull/5908

Once that update is available this will work properly.

@azat-io updated the sandbox. looks like they have some dev versions out that will work:

yarn add react-router@next react-router-dom@next

@probablyup Thank you! The problem with routing was resolved. There is only a problem with the warning about several instances of 'styled-components'

See the previous comment...
On Mon, Sep 24, 2018 at 7:32 AM Azat S. notifications@github.com wrote:

@probablyup https://github.com/probablyup Thank you! The problem with
routing was resolved. There is only a problem with the warning about
several instances of 'styled-components'


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/styled-components/styled-components/issues/1969#issuecomment-423958547,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiy1lckmdLkJaTp79nU9nNUc6Zq8azcks5ueNDQgaJpZM4WZ4nX
.

I am running into problems with using Mobx's observe() wrapper on a Styled component.
https://gist.github.com/ConneXNL/1e5bc6b0ae6e09ae7644ef1053e72bae

It seems console.log(StyledImage) returns a Plain object?:

{$$typeof: Symbol(react.forward_ref), render: ƒ, attrs: undefined, componentStyle: ComponentStyle, displayName: "Styled(Image)", …}

rather than what it did in Styled components 3:

StyledComponent() {
        classCallCheck(this, StyledComponent);
        return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments));
      }

Is this a new syntax? Mobx 4 does seem to be able to handle this object style. Check the Gitter for errors I got.

It returns a React.forwardRef object, yes. This sounds as though MobX needs to be updated to handle this case, as it'll be very common going forward.

I'm testing https://github.com/diegohaz/reuse with styled-components. It works really well on v3.4.9, but it's completely broken on v4, and I can't figure out the reason. 🤔

Demo: https://codesandbox.io/s/8ln735llpl (change styled-components version in the dependencies)

Reuse is pretty much this file. Maybe is React.forwardRef conflicting somehow? I'll try to investigate it further, but would appreciate if you guys have any clue.

@diegohaz seems ok to me? https://codesandbox.io/s/n5vz1jkqn0

That's weird, @probablyup. But it seems that your sandbox is still using v3. Inspecting it doesn't show Context.Consumer's for example (those ForwardRef come from Reuse):

image

I tested it removing ForwardRef's from reuse, but it still doesn't work. So that's not ForwardRef's conflicting.

You’re right, sandbox didn’t rebuild correctly. Weird.

Alright so I believe the issue is use hoists all the composite components together into one component and effectively deletes all but the rightmost styled component's styles since the statics of each get overwritten. Since we started doing folding in v4, we don't emit multi layered styled components anymore and the layering is why use was able to work with v3.

They probably shouldn't hoist statics if more than one component is being composed.

@probablyup Could you point me to some file/line/PR so I can understand it better?

You can see what I mean here: https://codesandbox.io/s/r5yl5kxow4

When a level of indirection is added to break the hoisting, it renders correctly. Here's the relevant code in reuse: https://github.com/diegohaz/reuse/blob/21d45e13576519b5787579b991125b13bf2bb8e8/src/use.tsx#L37-L39

So my recommendation would be for reuse to only hoist if it is composing one non-string component. 2 or more custom components should not be hoist-merged as it will cause unintended effects.

Hello all,

I am getting an issue when using withTheme. It seems that the component throws an error if ThemeProvider is not present even when defaultProps is defined.

I am using:
"styled-components": "^4.0.0-beta.9"

I am getting the following error:

Cannot read property 'theme' of undefined

I found this thread https://github.com/styled-components/styled-components/issues/538, but it seems that this issue has changed rather than be resolved.

Any help would be appreciated.

update

Looking into this it would appear that withTheme is using the defaultProps of the HOC rather than the WrappedComponent. https://github.com/styled-components/styled-components/blob/master/src/hoc/withTheme.js. I am guessing hoistNonReactStatic is not copying these as they are React props.

Please review and update if possible. I have tested this fix and it seems to be working well.
https://github.com/styled-components/styled-components/pull/2033

Thanks

We might delay release a week or so FYI - waiting for enzyme to cut a new version and also for some codemods to be finished to make the transition easier :)

Re:

@probablyup, that sounds great. Just wanted to let you know that I’m working on getting that repro for the SSR style order issue done. Just haven’t had time 😅

The issue seems to have magically disappeared even though we didn't upgrade Styled Components. If we run across it again I'll open an issue with a repro. But for now it seems that the issue is gone 👻

Lol! Well I'm glad the issue is gone anyway 🙈

on{X} is an established React pattern for passing events, so we don't filter it in case you want to pass onInput, onClick etc to the element. We can't possibly check every possible combination or the library would be quite bloated and probably unmaintainable, so we make some small compromises here and there where there's precedent.

@probablyup this is quite an unexpected change. I'm getting tons of warnings in the console like this:

Warning: Unknown event handler property `onboarding`. It will be ignored.
Warning: Unknown event handler property `onlineSize`. It will be ignored.
etc.
etc.

Those are obviously not event handlers and shouldn't be let through. I can't even filter them myself. 🙄

Could the heuristic be improved to only let on{UppercaseWord} through instead of every word that starts with on? /cc @mitchellhamilton I'm on styled-components beta 9 and @emotion/[email protected].

Hey,

I'm trying to implement the beta-10 (really wanted to use the as-prop). However, I noticed that when I try to do so, the prop 'as' is not recognised by Typescript. That could be due to the fact that there is only a package for version 3 on DefinatelyTyped?

I put together a small CodeSandbox to demonstrate my issue: https://codesandbox.io/s/w2rv2l1mp7
Is there a way to get around this right currently? I is not an option to add the as prop on the styled component as a prop I pass, since then I would lose the functionality if I for example use as={NavLink} (react-router), because I then need to type all the possible props it could accept.

Hoping there is already a solution in place and I'm just missing something :D

Thanks a lot!
Keep up the great work!

The update hasn’t landed yet: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/29389

But I’m unsure about the prop thing. cc @styled-components/typers

@probablyup Great! 👍 I'll give those typings a try before the'll be released! Didn't think if checking the issues over there, only checked all the branches..

I'm also having the same problem, @JeroenReumkens. I've created a detailed post about it on spectrum chat, which anyone can check out here.

ATM it looks like there isn't a good solution that will go out with the v4 release. @diegohaz offered a solution but only brief feedback has been given and it seems like @probablyup wants to get it out before the as issue is resolved.

not having support for the as prop in typescript is a dealbreaker, as it throws off my whole component composition pattern. not sure if i'll continue down this path or have to rip out typescript and use PropTypes 😕

Just tried out beta 11 and ran in the following problem:

image

Guess it is related to #2070 since it also only occurs in dev and the code is odly similiar ;) (but then again it does give you a slap in the face that you did something wrong)

Could you possibly post a code snippet that triggered the error to help me write a test case? It's hard to tell what actually triggered the error otherwise.

Took a while to find a minimal repoduction case but the following should work:

const SvgIcon = styled.svg`
    vertical-align: middle;
    height: ${props => (props.height ? props.height : '22px')};
    width: ${props => (props.width ? props.width : '22px')};
    text-align: center;
    font-size: 40px;
`;


ReactDom.render(
    <SvgIcon viewBox="0 0 512 512">
        <path d="M39.6,95.6z" />
    </SvgIcon>, container
);

Seems like it has something to do with the props attribute, this bare minimum also works:

const ElementWithProps = styled.div`
    height: ${props => (props.height ? props.height : '22px')};
`;
ReactDom.render(<ElementWithProps />, container);

Interestingly I can't reproduce it. A codesandbox would be fabulous if possible so I can hack on it.

I tried reproducing it in codesandbox but no luck (JS or TS), it simply works. I tried with CRA and there it also works. I will try CRA with TS (just to verify if it is TS related) else I will maybe have to take a dive into my webpack config or something.

I will try to get back asap.

Thanks! I also put up a PR to just wrap that code in a try-catch since it's a simple dev check and should never bust normal operations.

@DJWassink give 4.0.0-beta.11.1 a try

Sadly the same error, however I don't see any try/catch in 11.1, are you sure it has been correctly deployed?

I also seem to have found a reproductiable situation, just for a bit of a context I am working on a chrome-extension so I can target ES6 code (happy life), if I set my typescript target to ES5 it works correctly, I will soon upload a repo with some minimal code.

I am now heading to a meeting, I will get back to you in a minute.

Right so now that I found out the problem lies with the target for the TS compiler I also managed to reproduce the error in codesandbox

https://codesandbox.io/s/m452pn21ky

See the difference if you change the target in the tsconfig.json from es6 to es5.

@DJWassink looks to be fixed with latest beta: https://codesandbox.io/s/yj1vm0n6zx

Also keep in mind you need to use React 16.3+ with sc v4 for forwardRef

@JeroenReumkens v4 TS typings are now out: https://www.npmjs.com/package/@types/styled-components

Hi !

I'm trying to implement beta11 in a project of mine but I keep having the Stateless function components cannot be given refs. error when using ref.
I made sure we only use v4beta11 everywhere in the project and I was able to made a reduce test case if it can help: https://codesandbox.io/s/5kqkjlp69k

Don't know if the issue is on my side or comes from the beta so I might need a little help on that.

Any idea?

@tbekaert That's unrelated to v4 :) You're adding ref to a functional component. You probably either want to rename the prop and pass it on to the StyledComponent, or you might want to pass on a createRef ref instead, etc.

@kitten My bad ! I've update the codesandbox project accordingly but the issue is still firing

@kitten I managed to get it to work using React.forwardRef on CommonContainer https://codesandbox.io/s/5kqkjlp69k

Don't know why it is needed tho.

Anyway, thanks for your time :)
And keep up the good work, this rocks !

Thanks everyone for contributing during the beta process!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

gajus picture gajus  ·  46Comments

probablyup picture probablyup  ·  68Comments

nkbt picture nkbt  ·  48Comments

Nemsae picture Nemsae  ·  65Comments

JamieDixon picture JamieDixon  ·  42Comments