Home > Software design >  Use Different CSS for Different Routes In React
Use Different CSS for Different Routes In React

Time:11-20

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?

CodePudding user response:

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.

  • Related