Switching Next.js CSS class names with variables to CSS module class names - a simple guide

import Head from "next/head";
import Button from "../components/Button";

export default function Home() {
  return (
    <div className="main_content">
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Button
        onClick={() => console.log("You Clicked Me!")}
        type="button"
        buttonStyle="btn__primary__solid"
        buttonSize="btn__large"
      >
        Buy Now
      </Button>
      <Button
        onClick={() => console.log("You Clicked Me!")}
        type="button"
        buttonStyle="btn__warning__solid"
        buttonSize="btn__large"
      >
        Buy Now
      </Button>
      <Button
        onClick={() => console.log("You Clicked Me!")}
        type="button"
        buttonStyle="btn__danger__solid"
        buttonSize="btn__large"
      >
        Buy Now
      </Button>
    </div>
  );
}
@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap");

:root {
  --primary: #4628ff;
  --warning: #ffd129;
  --danger: #eb3f27;
  --success: #75fa83;
  --white: #fdfdfd;
  --dark: #181717;
}

*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  scroll-behavior: smooth;
  text-rendering: optimizeSpeed;
  line-height: 1.5;
}

.main_content {
  max-width: 1299px;
  min-height: 100vh;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 1rem;
}

.btn {
  font-family: "Roboto", sans-serif;
  font-weight: 400;
  border-radius: 10px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.btn:hover {
  transform: translateY(-3px);
}

/* colors & styles */
.btn__primary__solid {
  background-color: var(--primary);
  color: var(--white);
  border: none;
}

.btn__warning__solid {
  background-color: var(--warning);
  color: var(--dark);
  border: none;
}

.btn__danger__solid {
  background-color: var(--danger);
  color: var(--white);
  border: none;
}

.btn__success__solid {
  background-color: var(--success);
  color: var(--white);
  border: none;
}

.btn__primary__outline {
  background-color: transparent;
  border: 2px solid var(--primary);
  color: var(--primary);
}

.btn__warning__outline {
  background-color: transparent;
  border: 2px solid var(--warning);
  color: var(--warning);
}

.btn__danger__outline {
  background-color: transparent;
  border: 2px solid var(--danger);
  color: var(--danger);
}

.btn__danger__outline:hover {
  background-color: var(--danger);
  border: 2px solid var(--danger);
  color: var(--white);
}

.btn__success__outline {
  background-color: transparent;
  border: 2px solid var(--success);
  color: var(--success);
}
.btn__success__outline:hover {
  background-color: var(--success);
  border: 2px solid var(--success);
  color: var(--white);
}

/* sizes */

.btn__medium {
  padding: 10px 20px;
  font-size: 18px;
}

.btn__large {
  padding: 15px 30px;
  font-size: 20px;
}

const STYLES = [
  "btn__primary__solid",
  "btn__warning__solid",
  "btn__danger__solid",
  "btn__success__solid",
  "btn__primary__outline",
  "btn__warning__outline",
  "btn__danger__outline",
  "btn__success__outline",
];

const SIZES = ["btn__medium", "btn__large"];

function Button({ children, type, onClick, buttonStyle, buttonSize }) {
  const checkButtonStyle = STYLES.includes(buttonStyle)
    ? buttonStyle
    : STYLES[0];
  const checkButtonSize = SIZES.includes(buttonSize) ? buttonSize : SIZES[0];

  return (
    <button
      className={`btn ${checkButtonStyle} ${checkButtonSize}`}
      onClick={onClick}
      type={type}
    >
      {children}
    </button>
  );
}

export default Button;

This code works great with the globals.css file :-) But I want to convert this to css module.That's exactly that line of code:

className={`btn ${checkButtonStyle} ${checkButtonSize}`}

How to change, convert this className to css module className ?? My solution is like this :

className={`${styles.btn} ${styles.checkButtonStyle} ${styles.checkButtonSize}`}

Regrettably, my proposed solution did not work:/ Can anyone provide assistance? Thank you in advance!

Answer №1

I made the decision to include this code snippet to help others facing a similar issue. If we maintain the same class names in our *.module.css file, the solution will appear as follows:

className={`${styles.btn} ${styles[checkButtonStyle]} ${styles[checkButtonSize]}`}

Credit goes to @juliomalves for being the guiding force behind success. Huge thanks to @juliomalves, your support made all the difference.

Answer №2

classNames={[ styles[button], styles[checkButton--Style], styles[check__ButtonSize] ]}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

kindly utilize an array when writing your CSS using the BEM-block element modifier approach

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract data from JSON using the parse function

After utilizing the function JSON.stringify(), I have obtained this JSON: {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'== ...

Gradually conceal the final column of an HTML table with the combination of CSS and JavaScript

My challenge involves modifying a table on Sharepoint with responsive design in mind. The goal is to hide the last visible column in the table based on the screen's width. For instance, if a user creates a 10-column table and the screen size is 1200p ...

Pressing the "Ctrl" key, click on the link that will display a

I received a link that utilizes AJAX to render a partial view. Below is the code for the link: <a href="#" onclick="LoadChildCategories(@i.CategoryId, @i.IsTrading.ToString().ToLower())">@i.Name</a> Here is the code for the LoadChildCa ...

What is the best location to include my JavaScript code in WordPress?

Alright, so I've got this world map on one of my WordPress pages and here's an example of the code: <area onmousedown="modifyImage('world_map_01', './images/map/asia.jpg')" onmouseout="modifyImage('world_map_01', ...

Adding extra space in between navigation items within an unordered list using UL

Today is one of those days where I just can't seem to figure out why there is a space appearing to the left of each LI tag in the code below. Hover over the menu items and you'll see what I mean. Visit this link for more information <div id= ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Error encountered in Typescript React: JSON API Object expecting a ":" when indexing

Using Axios in Typescript React to fetch API Data. Here is a glimpse of the JSON Data :https://i.sstatic.net/DCXTz.png Trying to access the number value at index 1.tokenAmount.uiAmount Currently attempting data?[1]["tokenAmount"]["uiAmount"], but encoun ...

Choosing between Box, className, and style for vertical spacing in Material UI

Whenever I receive a design using Material UI, I always notice some vertical space between different elements like section headers, form labels, and input fields. Various methods can be used to achieve this: One way is to wrap each <Typography />, & ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Encountering "undefined" response while retrieving data from service in Angular 2

I'm experiencing an issue with my Angular 2 application where I am making an HTTP call in a service and trying to return the response back to the component. However, when I console log the response, it shows as "undefined". I have added a timeout to e ...

Working with button loops in react.js

Just started learning react.js and I'm trying to display a list of names as buttons. const exampleComponent: React.FC<IProps> = () => { const renderButtons= () => { for(let i=0; i<names.length; i++){ <TextButt ...

Checkbox click triggers a delayed update to the array

In my attempt to develop an array of user permissions that can be managed through a series of checkboxes, I encountered an issue. When I select a checkbox and use console.log() to display the array, it shows all the permissions I have checked. However, upo ...

Press the add button and then click on removeclass

My table structure is as follows: <table> <tr> <td>table 1 a <span class="icon"></span></td> </tr> <tr> <td>table 2 b <span class="icon"></span></td> & ...

Tips for updating the color of an active navbar:

<div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item mx-4"> <a class="nav-l ...

Utilizing a combination of CSS and JavaScript, the traffic light can be altered to change based on

**I stumbled upon this online code snippet where a timer is controlled in CSS. I'm trying to figure out how to control it with JavaScript, but all my attempts have failed so far. Is there anyone who can help me solve this issue? What I'm attempti ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

Execute a self-invoking JavaScript function with dynamic code

I'm facing a challenging problem that I just can't seem to solve... There's a function on another website that I need to use, but unfortunately, I can't modify it The code in question is: Now, I am looking to add a prototype "aaa" to ...

Obtain the location coordinates from Google Maps API using an ajax() call

I am attempting to retrieve longitude and latitude coordinates from the Google Maps API using the following example: http://jsbin.com/inepo3/7/edit. I am expecting a 'success' popup, but I keep seeing the 'Error' popup. The Google Maps ...

User-triggered event not being emitted back from SocketIO server

In my React frontend, I am using socket.io-client and in the Express backend application, I am utilizing socket.io. There is an event on the server that sends a message to all users in a room when triggered. socket.on('connection', () => { ...

Problem: Toggle functionality not working properly in JavaScript

As a beginner, I am facing an issue with multiple toggle buttons. They work fine individually, but when nested within each other, only one toggle button works. After some research, I realized that I need to make adjustments to my JavaScript code. However, ...