"Utilizing multiple class names in Next.js to enhance website styling

Looking for a way to apply multiple classNames in Next.js, especially when dealing with variable classnames?
I'm following the component level CSS approach.

Take a look at my code and what I aim to achieve:

import styles from "./ColorGroup.module.css";

const colors = ["red", "sky", "yellow", "green", "golden"];

const ColorGroup = () => {
  return (
    <div className={styles.colorContainer}>
      <text>Colour</text>
      <div className={styles.colorBoxContainer}>
        {colors.map((color, index) => (
          <div
            // The issue lies in applying both variable color classes and colorBox class. How can we do this?
            className={`${styles}.${color} ${styles.colorBox}`}
            key={index}
          ></div>
        ))}
      </div>
    </div>
  );
};

Achievement:

https://i.stack.imgur.com/kprnr.png

CSS snippet:


/* Code responsible for layout and arrangement as shown above */

.colorBox {
  height: 36px;
  width: 36px;
}

.red {
  background-color: lightcoral;
}
.sky {
  background-color: skyblue;
}
.yellow {
  background-color: lightyellow;
}
.green {
  background-color: lightgreen;
}
.golden {
  background-color: greenyellow;
}

However, the current method only applies the colorBox className while ignoring ${styles}.${color}. Any suggestions on how to apply both successfully?

Answer №1

It is recommended to utilize brackets for this scenario

<div className={styles.container} >
    {items.map((item, number) => (
        <div
            className={`${styles[item]} ${styles.box}`}
            key={number}
        ></div>
    ))}
</div>

Answer №2

If you want to add some style to your elements, consider using the style object and incorporating variables for easier customization:

<div key={index} className={`${styles.colorBox}`} style={{ backgroundColor: color }} >
</div>

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

Prevent users from clicking buttons until all mandatory fields are filled out using react-hook-form

I am seeking guidance on how to dynamically disable a button based on the input values of both Name and State in the given code snippet. Specifically, I want to restrict button functionality until both name and state fields are filled out, regardless of ...

Changing the line spacing of label elements in HTML forms

I am encountering an issue with my form where the spacing between the two lines of the <label> element is too large and I am unable to adjust the line-height. For reference, I have applied the same CSS styles to a <label> and a <p>. Surp ...

Animate your SVG with CSS using hover effects that originate from the center of the SVG

I successfully implemented this animation using GSAP and you can view the Codepen for reference: https://codepen.io/whitelionx/full/vYGQqBZ const svgs = document.querySelectorAll("svg"); svgs.forEach((svg) => { const tl = gsap .timelin ...

Tips for designing a navbar specific to a profile section

I am currently working on an angular application with a navigation bar composed of anchor tags. When the user logs in, I have an ngIf directive to display my profile icon with dropdown options. However, I am facing challenges in styling it correctly. I aim ...

The process of implementing sticky headers that stay in place while scrolling in a React application

I have a challenge with organizing tables based on date, using headers like (today, yesterday, last week, ...) and I want to make them sticky depending on the current table in the viewport. I attempted to implement this functionality using the react-sticky ...

displaying an item within a text field

I have an input box created using Angular reactive forms <input type="text" formControlName="OrgName" placeholder="Enter name" maxlength="60"> <p class="fieldRequired" *ngIf="showNameMSg" ...

Restoring the background color to its original shade following alterations made by jQuery

In my table, I have multiple rows with alternating white and grey backgrounds achieved through CSS. .profile tr:nth-child(odd) { background:#eee; } .profile tr:nth-child(even) { background:none; } However, I now want to allow users to select a row ...

Include a new feature within an onClick event

I'm looking to implement a single page application using React.js and I want to incorporate a list within a material-ui drawer. The goal is to dynamically add elements to an array every time a button is clicked, but I'm stuck on how to write this ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

What is the best way to position text in the center of a pie chart using Nivo for ReactJS?

Struggling to center the text with my pie chart on novio.rocks for my react project. Any tips or suggestions are appreciated! Check out the demo here. ...

Struggling with parsing a JSON object in ReactJS and looking for assistance

Seeking assistance from experts. I am in the process of developing an application that requires parsing every element of a JSON response fetched from an API. Here is the structure of the JSON: const data = [ { "status": 1, "from": "2021-03-09 ...

Incomplete width allocation for the floating div positioned to the left

I've encountered an issue with the placement of the side-text div in relation to the image. Currently, without specifying the width of the side-text div, it automatically moves to the bottom. To address this problem, I attempted using display:inline- ...

Using maxDate in Material UI DatePicker Component to set a maximum date limit

I'm having a tough time getting the maxDate property to function properly on the Material UI DatePicker component. It should disable dates after the specified maxDate. In my situation, I needed to set the maxDate to +60 days from the current Date(), ...

Using pure CSS to style sibling span elements in a unique color

Looking to change the color of a specific span based on the title attribute of another span in a different div. The code below successfully turns text2 red if it has the title of "Red". span[title=Red] ~ span { color: red; } <span title="Red" ...

Stop hyperlinks from automatically opening in a new tab or window

I'm having trouble with my website links opening in new tabs. Even after changing the attributes to _self, it still doesn't work. Can someone please review my code below and provide a solution? Feel free to ask for more clarification if needed. ...

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Conceal the div element when located beneath an ordered list with a designated

I need help hiding the display of comment information if it is a child comment. Below is my attempt to hide the div with the id "info" if the "ol" element has a class of "children". If you have another method for hiding the div when the comment is a chil ...

Tips on updating primeng Panel Menu appearance with scss

I'm looking to customize the color of my panel menu to black. Below is the HTML code I am using. <p-panelMenu styleClass="font-bold text-xs m-0 w-11" [model]="items" [multiple]='false'></p-panelMenu> ...