0

Currently, I am trying to implement a keen-slider library(https://www.npmjs.com/package/keen-slider). For installation, we need to add import 'keen-slider/keen-slider.min.css'. In that case, the keen slider CSS is added to global, as you know. The CSS is included globally in the page markup. From my perspective, it should be included only on pages where the slider is used

Is there any solution to solve this problem?

ZaO Lover
  • 433
  • 2
  • 13

2 Answers2

0

I'm not sure to understand the issue. You can always choose to import a file (CSS or whichever format you want) globally or in a specific file.

For your use-case, as soon as you install the dependency (npm install keen-slider --save), you will be able to import the minified CSS into the needed component. For example:

import React from 'react'
import 'keen-slider/keen-slider.min.css'
import { useKeenSlider } from 'keen-slider/react'

export function IndexPage(){
  const [sliderRef, slider] = useKeenSlider()

return <section className="slider-wrapper">
         <div ref={sliderRef}>
           <div class="keen-slider__slide">1</div>
           <div class="keen-slider__slide">2</div>
           <div class="keen-slider__slide">3</div>
         </div>
       </section>
}

With this approach, you will be only importing the keen-slider.min.css in the IndexPage.

Ferran Buireu
  • 28,630
  • 6
  • 39
  • 67
  • Thank you. The main problem is that if I import the css like above. The CSS imports to the global so it means that I can see this CSS on the pages. I don't want it. My goal is that import css to the only specific page. – ZaO Lover Mar 10 '21 at 15:39
0

I think, you can try to lazily load your component via:

const OtherComponent = React.lazy(() => import('./OtherComponent'));

Also you should do import 'keen-slider/keen-slider.min.css' inside of OtherComponent.

More info here: https://reactjs.org/docs/code-splitting.html

Vlad Diachenko
  • 387
  • 1
  • 8
  • Also you can try the solution from [this thread](https://stackoverflow.com/questions/45560806/react-load-components-css-only-when-component-is-rendered) – Vlad Diachenko Mar 10 '21 at 14:07