Next.JS - Conditionally Applying Classes

Viewed 14

All the solutions out there for this problem are so OP. Here's how to implement, using a module.css file.

Just create a ClassBuilder.js file some where and reference it. Keys in the class builder must be referenced from the

ClassBuilder.js

export class ClassBuilder {

    static build(obj) {
        return Object.keys(obj).filter((key) => obj[key]).join(" ");
    }

}

Usage

import styles from "./index.module.css";
     <div className={ClassBuilder.build({
                        [styles.inputContainer]: true,
                        [styles.focused]: focused,
                        [styles.hasPrefixIcon]: iconPrefix,
                        [styles.hasSuffixIcon]: iconSuffix,
                        [styles.error]: errors && errors[name]
               })}
      >
0 Answers
Related