Search code examples
cssreactjsmedia-queries

Is there a way to import a CSS file according to media in ReactJS


In a standard HTML file we can link multiple CSS's and then the browser will use the one that respects the media condition, for example:

<link rel="stylesheet" media="screen and (max-width: 600px)" href="mobile.css">
<link rel="stylesheet" media="screen and (min-width: 600px)" href="web.css">

Is it possible to do the same in ReactJS ? like :

import './web.css'; //for web
import './mob.css'; //for mobile
.
.
.
ReactDOM.render(<App/>,document.getElementById('root')); //main app

Thanks


Solution

  • you can try conditional Import

    if (window.innerWidth > 767) {
        import('./web.css').then(() => {
           console.log("Imported web css");
        });
    }
    else{
        import('./mob.css').then(() => {
           console.log("Imported mobile css");
        });
    }
    

    But I will recommend you to use media queries inside on CSS file which will be more handy in term of change