I have a Next JS 14 application – utilizing App router. The directory structure is something like the following
some-project/
├── app/
│ ├── layout.js
│ ├── page.js
│ └── ... (other app-related files)
├── components/
│ ├── xyz/
│ │ ├── xyzComponent.tsx
│ │ ├── xyzComponent.module.css
│ │ └── ... (other XYZ-related files)
│ ├── formElements/
│ │ ├── input/
│ │ │ ├── inputComponent.tsx
│ │ │ ├── inputComponent.module.css
│ │ │ └── ... (other input-related files)
│ │ ├── textarea/
│ │ │ ├── textareaComponent.tsx
│ │ │ ├── textareaComponent.module.css
│ │ │ └── ... (other textarea-related files)
│ │ ├── date/
│ │ │ ├── dateComponent.tsx
│ │ │ ├── dateComponent.module.css
│ │ │ └── ... (other date-related files)
│ │ ├── formElements.module.css
│ │ └── ... (other formElements-related files)
├── public/
│ └── ... (public assets like images, fonts, etc.)
├── styles/
│ ├── globals.css
│ └── ... (other global styles)
├── next.config.js
├── package.json
└── ... (other project-related files)
The formElements
components share some of the same styles (that I don’t want to repeat, can’t stress that enough) from the formElements.module.css
. Here is a sample file
// components/formElements/input/inputComponent.tsx
import React from 'react';
import formStyles from '../formElements.module.css';
import styles from './inputComponent.module.css';
const InputComponent: React.FC = () => {
return (
<div className={`${formStyles.container} ${styles.container}`>
<input className={styles.input} type="text" />
...
Now, the page loads perfectly the first time, applying the styles in the order they’re appearing here. When I move away from that page and come back again, Next JS reloads the formStyles
once again, but not the styles
. As a result, formStyles
gets precedence over styles
and messes up the style.
Here are my questions
- Why might they load
formStyles
but notstyles
in the second attempt? - If I should follow a pure
module
structure and utilize one.module.css
per file, what should I do about those common styles fromformStyles
? I can copy them and paste(/merge) it into all the nested folder’s.module.css
file underformElements
‘ – but I really don’t want to repeat styles. What would happen if I need to change the common styles later down the road, do I update all the nested files once again? - Any interesting idea for an alternative styling structure?
N.B. I want something other than !important
and style
property usage suggestions.
What I Did
I tried changing the order of the style imports, appearance in the className
– to no avail. I want either for formStyles
& styles
– both of them to reload in the given order, or not to reload them at all. My ultimate target is to reuse styles and get a consistent appearance.
Salman Hossain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.