Search code examples
cssreactjssassmaterial-uistyled-components

Attempted import error: 'createGlobalStyle' is not exported from 'styled-components'


I am try to import createGlobalStyle from styled-components but it does not seem to be working. I installed styled-components npm package, the version is @3.4.10.


const GlobalStyle = createGlobalStyle`
html {
    height: 100%
}
* {
    padding: 0;
    margin: 0
}

`
export default GlobalStyle

The above code is where I am trying to import createGlobalStyle

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import GlobalStyle from './theme/globalStyles'

ReactDOM.render(
  <React.StrictMode>
    <App />
    <GlobalStyle />
  </React.StrictMode>,
  document.getElementById('root')
)

And this is the index.js file where I am using the GlobalStyle component.

After running the code I am getting the following error:

./src/theme/globalStyles.js
Attempted import error: 'createGlobalStyle' is not exported from 'styled-components'.

Any help would be highly appreciated


Solution

  • If you're using styled-components version 3.4.10, then you have to use injectGlobal instead of createGlobalStyle, because createGlobalStyle was only release in v4 of styled-components. Check it out: [Deprecated] injectGlobal

    So, in order for your code to work, you have to change a few things:

    import { injectGlobal } from 'styled-components';
    
    const GlobalStyle = injectGlobal`
    html {
        height: 100%
    }
    * {
        padding: 0;
        margin: 0
    }
    `
    
    export default GlobalStyle
    

    And in your index.ts

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'
    import GlobalStyle from './theme/globalStyles'
    
    ReactDOM.render(
      <React.StrictMode>
        <GlobalStyle /> // this comes first
        <App />
      </React.StrictMode>,
      document.getElementById('root')
    )