3

I need to be able to use CSS in different routes in React. I would much prefer to not use SASS, but if it is the only solution I will use it.

My Homepage (index.js) needs to use index.css and my Other Page (page2.js) needs to use page2.css (example names)

File Structure:

-src
  -components
  -pages
     -css
        -index.css
        -page2.css
     -index.js
     -page2.js

Files:

// src/pages/index.js
import React from 'react'
import './css/index.css'

const Homepage = () => {
  return (
    <!-- unrelated HTML -->
  )
}

export default Homepage

// src/pages/page2.js
import React from 'react'
import './css/page2.css'

const Page2 = () => {
  return (
    <!-- unrelated HTML -->
  )
}

export default Page2

It really seems like this should work fine, but it loads both CSS files at once and they overlap and glitch out.

I would really like to avoid using things like SASS as stated above. Is there any way to do this with routes without doing something hacky like changing a link tag whenever the page changes?

2
  • CRA and vite should do this out of the box for you IIRC. Commented Nov 19, 2022 at 0:36
  • @super I don't think it does anymore, I have tried some re-ordering and it still keeps both stylesheets in one route. Commented Nov 19, 2022 at 0:49

1 Answer 1

4

I would strongly suggest you use css modules, css modules are just normal css files but applied to a css standarized structure to manage multiple css files among pages.

For this you should:

  1. Rename your css files to "homePage.module.css / page2.module.css"
  2. Move each css file to its page directory

It would look like this

-src
  -components
  -pages
        -page2.js
        -page2.module.css
     -index.js
     -homePage.module.css

Finally import each css file in its corresponding page Let me know if it worked for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much! It works well its just is tedious to convert all my classes to the module css classes.
This is a nextjs-only solution afaik. Do we have anything for react on its own?
Nevermind, works with React too (with Vite at least).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.