javascriptreactjsnext.jsimport

JS/React using a dynamic value for an import


Next.js comes with a bunch of "baked in" fonts that you can import like this:

import { Poppins } from "next/font/google";

const setFont = Poppins({weight: ['300'] , subsets: ["latin"] });

Then you can implement it into the font into the code like so:

    <html>
        <body className={setFont.className}>
          {children}
        </body>
    </html>

I would like to be able to do the import dynamically kind of like this:

let theFont= "Poppins"

import { {theFont} } from "next/font/google";

const setFont = theFont({weight: ['300'] , subsets: ["latin"] });

Ive tried to wrap it into a function which you cannot do with imports like this, as well as trying to get a dynamic value in the import statement which also did not work but I may have messed up the syntax


Solution

  • First thing that comes to mind is to import all the named exports via * then reference the particular symbol via your variable

    import * as fonts from 'next/font/google';
    
    let theFont = 'Poppins';
    
    const setFont = fonts[theFont]({ weight: ['300'], subsets: ['latin'] });
    

    Of course you lose out on any tree-shaking but that's the price you pay for it being dynamic.