Reputation: 7436
I need my css stylesheet split into many files, one per each Next.js page. How to implement this?
I tried to use next-css
and just import a css-file into each page. It almost works. However the css-file is not loaded on Link navigation. Authors of Next say it's not implemented:
https://github.com/zeit/next-plugins/issues/282#issuecomment-523128645
I also tried using styled-jsx
. It has several problems for me. It has many bugs on its Issues page. I also failed to make styles visible throughout child components with this approach.
Upvotes: 9
Views: 12418
Reputation: 109
I'm currently facing challenges with Next.js 13 due to the paradigm shift with server components, which prevents me from using CSS-in-JS like Styled Components. However, I'm exploring the use of CSS Modules. I'm sharing this here in case anyone has similar doubts. In the production build, they are indeed kept separate and are not bundled into a single file, which was a question I had. Furthermore, SCSS support in Next.js 13 is working well, with no additional configuration needed, which I'm not sure is the case in previous versions. I believe that just having SCSS support is a significant advantage.
Upvotes: 0
Reputation: 117
You can import a module.css
(import style from 'root/styles/MyStyle.module.css
) and use as follows.
This is your component:
import style from '../../styles/components/Header.module.css'
export default function Header() {
return (
<h1 className={style.header}>
Hello World
</h1>
);
}
This is your CSS:
.header{
color: #fff;
width: 100%;
height: 80px;
}
Note that the CSS class is used as the components className
;
Or, inside the react component, you can try adding the tag <style jsx>{ your_CSS_here }</style>
.
According to Next documentation each page uses the styled-jsx library. But you can still use other CSS-in-JS libraries such as Styled Components and Emotion.
Next apps has also support for using sass that allow you to import .css
and .scss
files.
For more information you can check the Vercel Docs. I also recommend you to check the Learning area.
Upvotes: 2
Reputation: 1416
You can create your seperate css files and on each component that you need specific styling you import the css file that is unique to that component. so for example say you have a Component in file file1.js
then you can import styles specific to this component in the file file1.css
same happens for another file file2
with css file2.css
import './file1.css'; //importing the style specific only for this component
function File1(){
const [processing, setProcessing] = useState(false)
return (
<> </>
)
}
export default File1
Similarly for the second file
import './file2.css'; //css file specific to this component
function File2(){
const [processing, setProcessing] = useState(false)
return (
<> </>
)
}
export default File2
Upvotes: 0