Nika Roffy
Nika Roffy

Reputation: 941

My component is not reading imported Slick CSS

I'm importing Sick carousel's CSS to my root component like this:

    import React from 'react'
    import PropTypes from 'prop-types'
    import { ThemeProvider } from 'styled-components'
    import { AppContext } from 'services/AppContext'
    import Layout from 'components/blocks/Layout'
    import { GlobalStyle, AppContainer } from 'shared/styles'
    
    import theme from 'theme'
    
    import 'slick-carousel/slick/slick.css'
    import 'slick-carousel/slick/slick-theme.css'
    
        function App({ Component, pageProps }) {
          return (
            <AppContext.Provider value={{ foo: 'bar' }}>
              <ThemeProvider theme={theme}>
                <AppContainer>
                  <GlobalStyle />
                  <Layout>
                    <Component {...pageProps} />
                  </Layout>
                </AppContainer>
              </ThemeProvider>
            </AppContext.Provider>
          )
        }
        
        App.propTypes = {
          Component: PropTypes.elementType.isRequired,
          pageProps: PropTypes.object.isRequired,
        }
        
        export default App

The problem is that the styles are not being applied to my carousel.

I have tried to import the CSS in the component which needs it, but next.js is giving me the error that either I have to import it in the root component or make it component level CSS, which I don't know how to do.

Any suggestions please?

Upvotes: 3

Views: 3646

Answers (1)

nghiaht
nghiaht

Reputation: 795

I also faced with this issue while using react-slick, it require few CSS from slick-carousel for the slider, navigation arrows...

Currently, I have two solutions:

  • Solution 1: Move the CSS import into root (pages/_app.js)
// _app.css
...
import 'slick-carousel/slick/slick.css'
import 'slick-carousel/slick/slick-theme.css'
...

// page/_app.js

...
import "./_app.css"
...

Comment: It makes react-slick working but the slick-carousel's CSS is loaded on all pages. Not so good!

  • Solution 2 (Preferred): Use the link tag and embed these CSS in your page's <head>
// I downloaded the CSS, minified them and put in the public folder
/public/static/css/slick.css
/public/static/css/slick-theme.css

// page/example.js

import Head from "next/head"

...
<Head>
// Embed local CSS
<link rel="stylesheet" type="text/css" href="/static/css/slick.css" />
<link rel="stylesheet" type="text/css" href="/static/css/slick-theme.css" />

// Or we can change the href to CDNs too
</Head>

Comment: We only embed and load styles in pages that we need, maybe it helps saving bytes.

Upvotes: 2

Related Questions