How to add global style option for a react UI library?

Viewed 358

I need to add global styling option for my react component library. I have added global style as shown below

import { createGlobalStyle } from 'styled-components';

export const  GlobalStyle = createGlobalStyle`

  button{
    color: white;
    background-color: green;
  }
`;

and I have exported the component so that app consuming the my-ui-libray can use it

export * from './GlobalStyle.js'

And I have used the global style as following in a react app

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { GlobalStyle } from 'my-ui-libray';

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <GlobalStyle/>
      <App />
  </React.StrictMode>
);

The issue is the CSS Styles are not applied to the button in the react app which is using my library. Is there any issue in my above code? Or is there a better way to achieve the same?

Note:

Global style work when the component in used in react Storybook as shown in following code, but once I build and use the library in the react app it does not work.

const Template = (args) => <><GlobalStyle /><Button {...args} /></>;  

Reference: (Add global styles section)

https://storybook.js.org/tutorials/design-systems-for-developers/react/en/build/

2 Answers

I find same issue on here enter link description here

you can try put your global style outside of strict mode

<GlobalStyle />
<React.StrictMode>
    <App />
</React.StrictMode>

or

<React.StrictMode>
    <NewComponent>
        <GlobalStyle />
        <App />
    </NewComponent>
</React.StrictMode>

my globalstyle can working in second solution

I also faces the same issue with styled components (version 5.3.5) when trying to create a UI library that exports a GlobalStyle component. The styles just won't applied when I imported it into the application. I am using rollup as the bundler. Not sure what causes the problem.

I switched to using emotion instead and the issue is resolved. Hope that helps.Emotion global styles guide

Related