Home > Enterprise >  styled-components - Why is global style injected after component styles here?
styled-components - Why is global style injected after component styles here?

Time:11-18

consider this example of a react-app using styled-components:

import styled from "styled-components";
import { createGlobalStyle } from "styled-components";
import React from "react";

const GlobalStyle = createGlobalStyle`
    [type="submit"] {
      color: red;
    }
`;

const StyledButton = styled.button`
  color: blue;
`;

function MyComponent() {
  return (
    <>
      <h1>My Component</h1>
      <button type="submit">regular button</button>
      <StyledButton type="submit">styled button</StyledButton>
    </>
  );
}

export default function App() {
  return (
    <>
      <GlobalStyle />
      <MyComponent />
    </>
  );
}

(See this codesandbox)

I'm setting a global style for elements (buttons) with [type="submit"] and want to override that style later with a StyledButton.

But styled-components seems to inject the global style AFTER the component style or at least prints it that way. If we inspect the <head> of the output with browser dev tools, we find:

.cshqdf{color:blue;}
[type="submit"]{color:red;}

This way, the blue color set by StyledButton is overridden by the global style. (The two css selectors have the same priority and therefore rely on order. I specifically used those selectors in my example to make the problem clear.)

My questions:

  • Why isn't the global style injected before the component styles? I expected this to be the case since <GlobalStyle/>is higher in the component tree.
  • How can I make sure, my global style is injected before the component style, so it can be overridden more easily?

Note: I'm totally aware that there are multiple ways to make StyledButton apply it's style while not caring about the order of style injections. One possibility would be of course:

const StyledButton = styled.button`
   && {
     color: blue;
   }
`;

However, solutions like that is NOT what I'm looking for. I'm trying to understand how to handle styled-component's global style in way such that selectors of equal priority (used for components) are coming afterwards in the style-sheet so I don't need additional tricks.

CodePudding user response:

This is a known bug:

https://github.com/styled-components/styled-components/issues/3146

You can look in the github issue for workarounds.

  • Related