How to add multiple classNames to nextjs elements
Solution 1
As stated in my original comment I have not worked with Next.js.
It appears as though styles is a map of some kind i.e.:
const styles = {
"projects-pd-subdetails-list": "Class Name A",
"projects-pd-text": "Class Name B",
"projects-pd-subdetail": "Class Name C"
}
This means that by using a line similar to styles["projects-pd-text projects-pd-subdetail"]
you are attempting to retrieve the value for the key "projects-pd-text projects-pd-subdetail"
which does not exist.
I would suggest retrieving the values individually from the map and then joining them together with your choice of string concatenation.
className={styles["projects-pd-subdetail"] + " " + styles["projects-pd-text"]}
// OR
className={`${styles["projects-pd-subdetail"]} ${styles["projects-pd-text"]}`}
Solution 2
You can use multiple className
like this
<li className={`${styles.projects-pd-text} ${styles.projects-pd-subdetail}`}>
{sub}
</li>
But there is a problem. It may throws an error(I guess, not sure). You may use camelCase
in your css className.
<li className={`${styles.projectsPdText} ${styles.projectsPdSubdetail}`}>
{sub}
</li>
or, if you don't want to camelCase
<li className={`${styles["projects-pd-text"]} ${styles["projects-pd-subdetail"]}`}>
{sub}
</li>
Let me know if it works.
Solution 3
A simple array join should suffice.
["class1", "class2", "class3"].join(" ")
result: "class1 class2 class3"
<li className={[styles.projects_pd_text, styles.projects_pd_subdetail].join(" ")}>
{sub}
</li>
Or save it as a variable for multiple uses
const listClasses = [styles.projects_pd_text, styles.projects_pd_subdetail].join(" ")
Solution 4
clsx is generally used to conditionally apply a given className.
Jevon Cochran
Updated on June 07, 2022Comments
-
Jevon Cochran almost 2 years
I have an unordered list element that looks like this:
<ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles["projects-pd-text projects-pd-subdetail"]} > {sub} </li> ))} </ul>
With a normal React element, I would be able to apply the multiple classes for the
li
element like this:<li className="projects-pd-text projects-pd-subdetail">{sub}</li>
However, having a space like I do in nextjs means the styles are just getting ignored. How can I fix this problem and properly account for two classNames for my
li
element here? -
Jevon Cochran over 3 yearsThis throws an error because it thinks I'm subtracting the variables pd and text from styles.projects in the first interpolation and the variables pd and subdetail from styles.proejcts in the second interpolation. Jacob Smit's comment above works though.
-
Robin over 3 years@JevonCochran thats why I suggest to use
camelCase
class name. -
Ahmad Alshaib almost 2 yearsYou can use snake_case works perfectly and is much more readable.