0

I am using React.

Usually, I am importing the whole css files in index.html within public folder.

But there is a css file that i cannot import globally (this is because web-publisher team worked on different pages and some of their css gets overriden)

Of course the best way to solve this would be to ask web-publisher team to unify their css work.

But i wanted to test if i could resolve this issue on my side (front-end)

How to import css for specific React component?

i tried this

import "../../../public/css/mypage.css/"

=> error: falls outside src directory

also this:

import "/public/css/mypage.css

=> also doesnt work

My solution: should i move this css file into my src folder?

My folder Structure: public folder => css => mypage.css public folder => index.html (where i usually import all css files)

src folder => App.js (i dont import css here)

jaehyuk kim
  • 121
  • 7
  • 1
    whereever and however you import it wont change the fact that it will be overiden by stronger css selectors – Ji aSH Aug 30 '22 at 06:24
  • And no matter i try to import css for specific component, the css works always globally within react framework right? – jaehyuk kim Aug 30 '22 at 06:28
  • yes, react doesnt have any CSS encapsulation natively to my knowledge. – Ji aSH Aug 30 '22 at 06:31
  • what is your folder structure? where is css and where is your react component? – Amit Khanna Aug 30 '22 at 06:38
  • ive edited my folder structure in the question. basically i have css files in public folder where i import into index.html which is in public folder. – jaehyuk kim Aug 30 '22 at 06:54
  • Have you tried `import "/css/mypage.css"` yet? – blurk Aug 30 '22 at 06:55
  • i get an error: Module not found: Error: You attempted to import /css/mypage.css which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/. – jaehyuk kim Aug 30 '22 at 07:02

1 Answers1

0

It's weird that i tried to import like you (import "../../../public/css/mypage.css/"), it worked. Maybe you want to check the path to see if it was correct. enter image description here

blurk
  • 235
  • 2
  • 6
  • no no the problem is even if you import specific css for a component within React, that css will apply for the entire React app because React is a single page application. Hence, my understanding is importing css for specific component is not possible in React. – jaehyuk kim Aug 30 '22 at 13:32
  • Ohh, maybe you wanna check out css modules. And check out [this answer](https://stackoverflow.com/a/47090832/13329040) – blurk Aug 30 '22 at 16:55
  • 1
    O thanks so much so basically i need to use css module. Still, i think the web publisher should unify their work before giving their work to front-end. – jaehyuk kim Aug 31 '22 at 02:10