Next.js Discord

Discord Forum

How to dynamically import CSS based on server side prop

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
Suppose following global css files which set-up BRAND specific variable values:

src/css/brand-a.css
src/css/brand-b.css


example of contents (/src/css/brand-a.css):
:root {
  @mixin theme-brand-a;
}

and my src/pages/_app.tsx
type OwnPageProps = {
  brand: "a" | "b"
};

const MainApp = ({ Component, pageProps }: AppProps<OwnPageProps>) => {
      const { brand } = pageProps;
      // Need to import brand-specific css
      return   <Component {...pageProps} />
}

## Attempt 1:
import from "src/css/brand-a.css"
import from "src/css/brand-b.css"

## FAIL:
CSS Results in one huge style.css with global styles overwritting each other

## Attempt 2 (trick the next/dynamic to load global as module):
src/components/CssLoaderBrandA.tsx
src/components/CssLoaderBrandA.module.css
src/components/CssLoaderBrandB.tsx
src/components/CssLoaderBrandB.module.css
src/components/CssLoader.tsx


Example of CssLoaderBrandA.ts:
import React from 'react';
import './CssLoaderBrandA.module.css';

const CssLoaderBrandA = () => <p />;

export default CssLoaderBrandA;


Example of src/components/CssLoader.tsx:
export const CssLoader = ({ brand }: CssLoaderProps) => {
  switch (brand) {
    case 'A':
      dynamic(() => import('./CssLoaderBrandA'));
      break;
    case 'B':
    default:
      dynamic(() => import('./CssLoaderBrandB'));
      break;
  }
  return <p />;
};


Example of src/pages/_app.tsx
const MainApp = ({ Component, pageProps }: AppProps<OwnPageProps>) => {
      const { brand } = pageProps;
      // Need to import brand-specific css
      return  <>
            <CssLoader brand={brand} />
            <Component {...pageProps} />
      </>
}

## FAIL: Syntax error: Selector ":root" is not pure (pure selectors must contain at least one local class or id)

## Attempt 3:
Alter webpack to remove ALL css/sass/scss loaders and rules and define own chunks for css and load them as 'asset/resource'
## FAIL:
All css 404

2 Replies

American Chinchilla
Why not just combine it into one file and use css modules
Northeast Congo LionOP
As stated in the thread, each brand hosts its own values for variables eg
brand-a.css
:root {
--var-primary-color: red;
}

brand-b.css
:root {
--var-primary-color: blue;
}

depending on the domain name eg brand-a.com, brand-b.com, i infer which brand it is and need to load the appropriate global css file for the whole app.

The components themselves then use indeed css modules and refer to those global variable values eg:
src/components/Button.module.css

background-color: var(--var-primary-color); etc