How to add stylesheet in Next.js ?
NextJs is a React-based framework that provides developers with all the tools required for production. Next.js is a react-based framework. It has the powers to Develop beautiful Web applications for different platforms like Windows, Linux, and mac.
In this post, we are going to learn about adding stylesheet in NextJs. Stylesheet are used to design the webpage to make it attractive and are the reason to simplify the process of making web pages presentable.
Creating NextJs application:
Step 1: To create a new NextJs App run the below command in your terminal:
npx create-next-app my-next-app
Step 2: After creating your project folder (i.e. my-next-app ), move to it by using the following command:
Project Structure: It will look like this.
In this post, we have used all the CSS files present in styles folder, components/Navbar.js, pages/_app.js and pages/index.js.
To import a global CSS file the following syntax is used:
To import a CSS module, the following syntax is used:
import custom_var_name from "filepath";
And now to use styles applied in the filepath in the CSS module you can refer to that by:
Adding the stylesheets: The initial look of our app is given below:
Adding global stylesheets: To add a global stylesheet in a Next Js app, basically, the CSS rules which will apply to the entire app, just import the CSS file to the pages/_app.js.
For example, we have a CSS file named “style.css” in our “styles” folder. The CSS file looks like this:
And let us now import it in our “pages/_app.js” file by the following command:
Currently, our “pages/_app.js” looks as shown below:
And by adding the stylesheet, our app applies the css rules and looks as shown below:
Note: If you don’t already have a “pages/_app.js” file then create one and add the following code to it:
Adding component-level CSS: Next Js also supports adding component-level CSS in your app. It supports CSS modules using the “[file].module.css” naming convention. This method of using CSS modules allows scoping the styles locally to a component by automatically creating a unique classname as well as using multiple styles with the same classname.
CSS modules can be imported anywhere in the application.
Example: Let us have a file named “navbar.module.css” in our “styles” folder.
The code of our CSS file is as follows:
And now let us add this “current” class to our “components/Navbar.js” file by importing and then adding the class.
Output: After adding the component to the index page the output is:
Importing styles from node_modules: To import global styles sheets as supposed in bootstrap, you can simply add your import statement to your “pages/_app.js” file as shown above. You can also import CSS required by third-party components in your component by adding the following import statement to your component:
// Inside "component/YourComponent.js" import "filepath" // Example import '@reach/dialog/styles.css'