Search code examples
reactjssassnext.jscss-modules

How can I toggle a class and change the CSS in Nextjs?


I'm working on a Next.js project where the menu opens with a <p> toggling the menu class. I managed to do this, but when I add the class in the CSS it doesn't take into account both classes.

This is my code:

Component

import { useState } from "react";
import styles from "../styles/modules/header.module.scss";

export default function Component() {
    const [isModal, setIsModal] = useState(false);
    return (
        <div>
            <p onClick={() => setIsModal(!isModal)}>Menu</p>

            <div className={`${isModal && "nav-open"} ${styles.ModalContainer}`}>
                Content
            </div>
        </div>
    );
}

SCSS

.ModalContainer {
    position: absolute;
    left: -100vw;

    &.nav-open {
        left: 0;
    }
}

When I inspect the code I can see that it adds the class when I click on the menu button, but can't see the expected changes. Does someone have a solution?


Solution

  • You need to use the class from your scoped Sass module file, in this case styles["nav-open"]. Simply setting "nav-open" will refer to a global class, which probably doesn't exist.

    export default function Component() {
        const [isModal, setIsModal] = useState(false);
        const contentClassname = isModal
            ? `${styles["nav-open"]} ${styles.ModalContainer}`
            : styles.ModalContainer;
    
        return (
            <div>
                <p onClick={() => setIsModal(!isModal)}>Menu</p>
                <div className={contentClassname}>Content</div>
            </div>
        );
    }