CodeRocks
CodeRocks

Reputation: 715

Dynamic Imports Based on this.props in React

In my NextJS app, I have node_modules (js files) for themes for certain elements on the page. I want to load only the files I need this based on this.props.theme for the component. How/where would I do this in my component. Basically, if I have a bunch of files for themes:

theme-red.js
theme-orange.js
theme-yellow.js
theme-green.js
theme-blue.js
theme-purple.js
theme-violet.js
theme-pink.js
theme-rainbow.js

In the props, I would this.props.themepassed in and then load in require(theme-${this.props.theme}.js)

Upvotes: 1

Views: 741

Answers (1)

Utkarsh Singh
Utkarsh Singh

Reputation: 36

You can use the import function:

const theme = await import(./{path-to-the-files}/theme-${this.props.theme}.js)

It would be good to include this in the componentWillMount function of the component.

https://nextjs.org/docs/advanced-features/dynamic-import
https://javascript.info/modules-dynamic-imports

Upvotes: 1

Related Questions