Search code examples
cssreactjsmedia-queriescss-modules

media query doesn't work properly with css modules when using an arbitrary class name


I'm doing a react course project and I'm doing everything exactly as the tutorials say, and media query in some circumstances doesn't work.

here's the short version of my js file (where NavigationItems is my custom element)

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

const toolbar = props => (
  <header className={styles.Toolbar}>
    <NavigationItems className={styles.Foo} />
    <p>some text</p>
  </header>
);

i want my NavigationItems to not be displayed when using mobile devices, so the css file which contains my styles includes this media query:

@media (max-width: 499px){
    .Foo {
        display: none;
    }
}

and surprisingly it doesn't work and doesn't apply the Foo class. however if i change the media query to this:

@media (max-width: 499px){
    .Toolbar{
        display: none;
    }
}

it does work and the Toolbar disappears when the width is smaller than 500px. but I don't want this; I want the Toolbar to be there and just the NavigationItems to disappear.

one other think that does work is when i change the media query to this:

@media (max-width: 499px){
    .Toolbar p{
        display: none;
    }
}

and the paragraph containing "some text" inside the js file disappears when it should. But still, the same thing wouldn't work for NavigationItems (and I'm guessing because of its not a default HTML tag).

I'm using [email protected] and other forms of styling work perfectly fine when I'm using CSS modules, the only problem is when I use media queries for arbitrary class names.

does anyone know how to solve this issue and why this doesn't work?


Solution

  • NavigationItems is React component and therefore does not work with styles and className. className is prop as any other in your React component. Unless you process it in your custom component, it will not work.

    const NavigationItems = (props) => {
      const {className} = props
      return (<div className={className}>This is your styled item</div>)
    }