Using a CSS Module Class as a Variable in NextJS

Apologies in advance if I miss any details - this marks my debut post on Stack Overflow.

The main objective of the function is to operate my hamburger menu, either opening or closing it. I have shared a snapshot of the JSX file pertaining to this issue: NavbarLinks.jsx. The problematic lines of code are 15 and 18 where I am attempting to declare a CSS module class as a variable.

const [navLinkOpen, navLinkToggle] = useState(false);
  const handleNavLinksToggle = () => {
    navLinkToggle(!navLinkOpen);
  };

let classes = {`${styles.navLinks}`};

if (navLinkOpen) {
  classes += {`${styles.active}`};
}

return classes;
};

Subsequently, I reference the returned class within the ul tag on line 27.

<ul className={renderClasses}>

I've experimented with various ways of defining this class as a variable, and what you see here is my latest attempt. I acknowledge that this particular attempt has disrupted the code - still getting the hang of JavaScript and prefer learning through trial and error rather than solely relying on tutorials from platforms like YouTube.

Please tackle the question at hand rather than suggesting alternate methods, as my primary aim is to enhance my understanding in this area! Nonetheless, I'm open to exploring alternative approaches that achieve the same goal as well.

Including a link to the CSS Module file I'm currently working on just in case it proves helpful: NavbarLinksStyle.module.css

Many thanks in advance for any assistance - I'll be available to address any queries.

Answer №1

Congratulations on your post! The explanation is very clear. Your code looks good overall, but it seems like you forgot to execute the renderClasses function.

const [navLinkOpen, navLinkToggle] = useState(false);
  const handleNavLinksToggle = () => {
    navLinkToggle(!navLinkOpen);
  };

  const renderClasses = () => {
    let classes = styles.navLinks;

    if (navLinkOpen) {
      classes += styles.active;
    }

    return classes;
  };

  {...}
    <ul className={renderClasses()}> 
  {...}

You can also achieve the same outcome by using a variable instead of a function:

const renderClasses = `${styles.navLinks} ${navLinkOpen ? styles.active : ''}`;

UPDATE: As suggested by @Mina, you should remove the curly braces from your render function.

Answer №2

It is important to avoid defining the variable using curly braces in this scenario.

  const updateClasses = () => {
    let classes = styles.navigationLinks

    if (isNavLinkOpened) {
      classes += styles.active
    }

  return classes;
};

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

Process for arranging an array according to the sorting sequence of another

Using two arrays in a Highcharts "series" parameter, for example: X = [25, 100, 50, 12] Y = [50, 12, 100, 25] The sequence of X and Y corresponds to the chart's Y value. When sorting X in ascending order, Y's order should match by becoming: X ...

Having trouble transmitting information to a php script using $.post()?

I have set up a shopping cart functionality on my website. Here's how it works: On the catalog page, there are four products, each with its own "Add to Cart" button. When a user clicks on one of these buttons, an onClick attribute calls the addToCart( ...

Tips for retrieving the dynamically generated ID within an li tag

I've been diving into the world of JavaScript and jQuery, encountering a few hurdles as I attempt to merge various solutions that I come across. This code represents a mishmash of tutorials I've recently completed. Admittedly, I am quite new to ...

Minimize the amount of space between two heading elements

Is there a way to decrease the distance between two heading tags? I want the h2 tag to be nearer to the h1 tag. Here is the CodeSandbox link for reference: https://codesandbox.io/s/rough-framework-tsk5b ...

techniques for presenting tabular data in a JavaScript modal

Hey there! I'm looking for a way to show table formatted data in a JavaScript popup. Do you know if it's possible to display table formatted data in a JavaScript popup using ASP.NET and C#? ...

Retrieve JSON-formatted HTML content to display as HTML within a React component

Wondering how to make the link actually render as a clickable hyperlink. Currently, when I read this line of text from my Json file, React displays the link as plain text rather than a clickable link. someData.json [{ "about": "John has a blog you ...

The online server is unable to access the route from the ajax function in a separate JavaScript file

I am currently working on a Laravel project where each view page has its own separate JS file. However, I have encountered an issue when trying to access route functions from AJAX post or get calls on the online server (Digital Ocean). The error message I ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Creating an accessible order for the next and back buttons

Currently, I am working on designing the user interface for a checkout flow. Towards the end of the page, there are 3 buttons available - Next, Back, and Cancel. When viewed on a desktop, the button layout appears as follows: (Back) (Next) Cancel http ...

Align the content in the center vertically unless it is bigger

Currently, I am working on a small project involving a responsive website that utilizes the Skeleton responsive grid. To ensure that the content is centered vertically in the viewport, I am using jQuery. <script> $(document).ready(function(){ ...

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

Preventing SQL Injection by properly formatting SQL queries

In my Node.js application, I need to construct an SQL query that looks like the one shown below. SELECT * FROM my_table WHERE my_column IN ['name1','name2'] The user inputs an array, such as ['name1', 'name2'], whic ...

Implementing a color filter on a camera using Three.js

Can a parameter be adjusted for the camera or renderer to apply a tint to everything on the stage, such as a red shade resembling a "glasses effect", without having to manually modify each object's materials? ...

What is the best method to align the three wrappers consecutively?

<div id="container" style="width:900px"> <div id="wrapper1" style="width:200px;float:left"> <img src="./profilepic.jpg" width="190px" height="220px"/> </div> <div id="wrapper2" style="width:400px;float:left"& ...

Retrieve the text from the outer span excluding any text from the inner elements

I am looking to retrieve specific text from an HTML element using Selenium and Javascript. <span class="myAttribute"> <b>SomeValueToIgnore</b> <span class="ignoreWhatsInside"> <em>ignore_that</em> </span& ...

Getting access to a variable on the client side using express-expose

I'm looking to assign a JavaScript variable on my index.html page once it's returned by express.js. I've attempted to utilize the express-expose middleware, but I'm struggling to figure out how to set the variable in the static HTML pag ...

Creating a cutoff with CSS: A step-by-step guide

Is there a way to create something similar using only CSS? https://i.stack.imgur.com/N9c6W.png I have no clue on how to achieve this. Any assistance would be greatly appreciated. ...

The functionality of a JQuery post within a PHP loop is not functioning optimally

I am encountering an issue with my list.php file, which generates a list with items and a button (Erledigt!) that triggers a jQuery Post to wishdelete2.php. The problem is that the jQuery post sometimes requires multiple clicks (3x or 5x) before it process ...