Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 589
JulSeb42 Avatar asked Oct 19 '25 16:10

JulSeb42


1 Answers

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>
    );
}
like image 70
juliomalves Avatar answered Oct 21 '25 04:10

juliomalves