How To Implement Multiple Classnames In NextJS ?
Last Updated :
14 May, 2024
When styling components in Next.js, it's common to encounter scenarios where you need to apply multiple classnames for different styling purposes. To implement multiple classnames in Next.js, you can utilize either the built-in classnames
package or any other utility library like clsx
.
We will discuss the different approaches to Implementing Multiple Classnames in NextJS:
Step to Create a NextJS App
Step 1: First, create a new NextJS project by running the following command in your terminal:
npx create-next-app <project-name>
Step 2: Navigate into the project directory:
cd <project-name>
Project Structure:
Project StructureThe Updated dependencies in your package.json file is.
"dependencies": {
"next": "14.2.3",
"react": "^18",
"react-dom": "^18"
},
Using String Interpolation or Concatenation
Initially, beginners often follow this approach. However, they quickly encounter challenges with maintenance and readability, particularly when working with TailwindCSS for styling, which exacerbates the issue.
Update Page.js and make Home.module.css and button.module.css in styles folder for adding css.
Example: Below is an example to implementing Multiple Classnames In NextJS Using String Interpolation or Concatenation.
CSS
/* styles/button.module.css */
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
.active {
background-color: #28a745;
}
CSS
/* styles/button.module.css */
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
.active {
background-color: #28a745;
}
JavaScript
// page.js
import styles from './styles/Home.module.css';
import buttonStyles from './styles/button.module.css';
export default function Home() {
const isActive = true;
// Define multiple classNames using string interpolation or concatenation
const buttonClass = `${buttonStyles.button} ${isActive ? buttonStyles.active : ''}`;
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to
<a href="https://www.geeksforgeeks.org/">Geeksforgeeks!</a>
</h1>
<button className={buttonClass}>Click Me</button>
</main>
</div>
);
}
Output:
button effectUsing Utility Packages (`classnames` or `clsx`)
Presently, two utility packages address the aforementioned issue: classnames and clsx. Functionally, they are identical, with clsx being slightly smaller than classnames. Both packages weigh in at less than 500 bytes, rendering the choice inconsequential. It's merely a matter of preference to determine which package name exudes more appeal.
Install the required packages using the below command.
npm install classnames
or
npm install clsx
The Updated dependencies in your package.json file is.
"dependencies": {
"classnames": "^2.5.1",
"clsx": "^2.1.1",
"next": "14.2.3",
"react": "^18",
"react-dom": "^18"
},
In case of - Using `classnames`
Example: Below is an example to implementing Multiple Classnames In NextJS Using 'classnames'.
CSS
/* styles/button.module.css */
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
.active {
background-color: #28a745;
}
JavaScript
// page.js
import React from "react";
import styles from "./styles/button.module.css"; // Import CSS module
export default function Home() {
const isActive = true;
// Define classNames using classnames package
const buttonClass = isActive ? `${styles.button} ${styles.active}` : styles.button;
return (
<div>
<h1>Welcome to Next.js!</h1>
<button className={buttonClass}>Click Me</button>
</div>
);
}
In case of - Using `clsx`
Example: Below is an example to implementing Multiple Classnames In NextJS Using 'clsx'.
CSS
/* styles/button.module.css */
.button {
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: #0056b3;
}
.active {
background-color: #28a745;
}
JavaScript
// page.js
import React from "react";
// Import clsx
import clsx from "clsx";
import styles from "./styles/button.module.css";
export default function Home() {
const isActive = true;
// Define classNames using clsx
const buttonClass = clsx(styles.button, {
[styles.active]: isActive
});
return (
<div>
<h1>Welcome to Next.js!</h1>
<button className={buttonClass}>Click Me</button>
</div>
);
}
Output:
Classname and clsx -same outputConclusion
With these approaches, you can easily manage multiple classnames in your Next.js components, making styling more flexible and efficient. Whether you choose string interpolation or utility packages, these methods provide convenient solutions for styling your Next.js applications.
Similar Reads
How to implement class constants in TypeScript ?
In this article, we will try to understand how to create several class constants (properties with constant values) in TypeScript with the help of certain code examples for better concept understanding as well as clarification. Let us first understand quickly how we may create a class in TypeScript w
3 min read
How to implement inheritance in ES6 ?
In this article, we will know how inheritance is implemented in es6. The ES6 JavaScript supports Object-Oriented programming components such as Object, Class and Methods. Further in Classes we can implement inheritance to make child inherits all methods of Parent Class. This can be done using the ex
2 min read
How to implement inheritance in Node.js bindings?
Node.js serves as a robust runtime environment, empowering developers to construct server-side applications that are both scalable and efficient. One of its key features is the ability to bind to C or C++ libraries, providing a bridge between JavaScript and lower-level languages. In this article, we
3 min read
How To Setup Multiple Layouts In NextJS?
Next JS Layout components are commonly used to structure the overall layout of a website or web application. They provide a convenient way to maintain consistent header, footer, and other navigation elements across multiple pages In this article, we will learn to set up Multiple Layouts in NextJS. T
4 min read
How to add or remove multiple classes to a ReactJS Component?
In react we offen need to add or remove multiple classes based on the state and props to update the content dynamically. It can be done with the help of template-literals, className property and by using external npm packages. How to Add or Removed Classes in React?To add or remove multiple classes
4 min read
How to Open a Link in a New Tab in NextJS?
Opening a link in a new tab in Next.js consists of using either the target="_blank" attribute in an anchor (<a>) tag or using Next.js's Link component with the passHref prop to ensure proper handling of routing while opening the link in a new tab. In this article, we will explore both these ap
3 min read
Ember.js Component classNames Property
Ember.js is an open-source JavaScript framework used for developing large client-side web applications which are based on Model-View-Controller (MVC) architecture. Ember.js is one of the most widely used front-end application frameworks. It is made to speed up development and increase productivity.
3 min read
How to Implement a Custom Promise in JavaScript ?
A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error. Table of Content Using Class SyntaxUsing Factory Fu
3 min read
How to add Image Carousel in Next.js ?
In this article, we are going to learn how we can add an Image Carousel in NextJS. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. ApproachTo create image carousel in next.js we are going to use a react-r
2 min read
How to import SASS in Next.js ?
Sass is the short form of Syntactically Awesome Style Sheet. It is an upgrade to Cascading Style Sheets (CSS). Sass is a CSS pre-processor. It is fully compatible with every version of CSS. Importing SASS in Next.js allows you to use SCSS for styling your application. This integration enables advanc
2 min read