Reputation: 59
I'm now trying to choose which css file to apply using next.js.
I have two css files, one for pc, and one for mobile.
Currently, I am importing css file like below:
// _app.tsx
import "../styles/globals.css"; // pc styling css
// import "../styles/globals_mobile.css"; // mobile styling css
function MyApp({ Component, pageProps }: AppProps) {
// ... remaining code
}
Now I have mobile css styling file, and I have isMobile
boolean variable which identifies that the device is pc or mobile from AppProps
.
But I couldn't find a way how to import css file dynamically.
The below is pseudocode, it is not actually working:
// _app.tsx
import pcStyling from "../styles/globals.css"; // it is NOT actually imported.
import mobileStyling from "../styles/globals_mobile.css"; // it is NOT actually imported.
function MyApp({ Component, pageProps }: AppProps) {
if (pageProps.isMobile) apply mobileStyling;
else apply pcStyling;
// ...
}
Is there an option I am able to choose?
Upvotes: 0
Views: 572
Reputation: 35553
Since your styles are static, you can put them inside the public
folder.
And inject the proper link to them inside <Head>
component.
This should look similar to this:
// _app.tsx
import Head from 'next/head';
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<Head>
<link rel="stylesheet" href={`/styles/globals${pageProps.isMobile ? '_mobile' : ''}.css`} />
</Head>
{'rest of your components'}
</>
);
}
The code above assumes that inside public
folder there is /styles/globals.css
& /styles/globals_mobile.css
files
Upvotes: 1