Home > Mobile >  Declaring a CSS Module Class as a Variable in NextJS
Declaring a CSS Module Class as a Variable in NextJS

Time:06-27

Please excuse me if I forget anything - this is my first post on Stack Overflow.

The function's purpose is to open and close my hamburger menu. I have attached a snapshot of the JSX file where this issue is: NavbarLinks.jsx. The lines of code that I am struggling with are 15 and 18 where I am trying to declare a CSS module class as a variable.

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

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

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

    return classes;
  };

I then call the returned class inside the ul tag on line 27.

<ul className={renderClasses}>

I have tried several variations of declaring this class as a variable, what I am showing you here is just my last attempt. I am aware that the attempt I am using has broken the code. - I am fairly new to JavaScript and instead of simply following YouTube guides, I learn better by trying things myself.

Please try and answer the question I have instead of suggesting an alternative method, purely because I just want to learn more about this! - but if you do have alternative methods of what I am trying to achieve here, I would very much like to see them too.

I'll also include a snapshot of the CSS Module file that I am working with just incase you may find it useful: NavbarLinksStyle.module.css

Thanks in advance for any help - will be around to answer any questions.

CodePudding user response:

first of all, congrats on the post. It's very well explained. The code you shared seems to be pretty fine overall, but from what I can see you are missing the execution of 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()}> 
  {...}

Also, you can achieve the same result by using a variable instead of a function:

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

EDIT: Also as @Mina pointed out you should get rid of the curly braces on your render function.

CodePudding user response:

First of all, you shouldn't declare the classes variable with curly brackets.

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

    if (navLinkOpen) {
      classes  = styles.active
    }

  return classes;
};
  • Related