Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React css modules - Applying styles to native html tags

Tags:

css

reactjs

This is pretty straightforward. Let's say I have some NavBar component:

import React from 'react';
import styles from './NavBar.module.css';

export default function NavBar() {
    return(
    <nav className={styles.nav}>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </nav>
    );
}

And now I have a NavBar.module.css file:

.nav {
    display: flex;
    padding: 20px;
    background: #6dd3d6;
}

But since I am using the semantic tag and the benefit of using css-modules is that they cannot cause name interference, is it somehow possible to directly style the nav without having to pass the styles class?

Like

import styles from './NavBar.module.css';

export default function NavBar() {
    return(
    <nav>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </nav>
    );
} 

with

 nav {
        display: flex;
        padding: 20px;
        background: #6dd3d6;
    }
like image 888
Leviathan Avatar asked May 22 '26 10:05

Leviathan


1 Answers

I think you could do something like.

import React from 'react';
import styles from './NavBar.module.css';

export default function NavBar() {
    return(
    <div className={styles.nav_container}>
      <nav>
          <ul>
              <li>Item 1</li>
              <li>Item 2</li>
              <li>Item 3</li>
          </ul>
      </nav>
    </div>
    );
}

in your css module file (NavBar.module.css) you could do

.nav_container nav {
      display: flex;
      padding: 20px;
      background: #6dd3d6; 
 }
.nav_container ul{
    /* for example */
    list-style: none;
}

.nav_container li{
      /* for example */
      font-size: large;
}

although you'll write nav_container many times in the css file it's more manageable and copy-able, than putting className on each jsx tag.

of course instead of the extra div you can do

<nav className={styles.nav}>
   <ul>
       <li>Item 1</li>
       <li>Item 2</li>
       <li>Item 3</li>
   </ul>
</nav>

and the css module file

.nav{
        display: flex;
        padding: 20px;
        background: #6dd3d6;
}

.nav ul{

}

.nav li{

}
like image 130
kataya1 Avatar answered May 25 '26 01:05

kataya1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!