Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally import file in Reactjs

Tags:

reactjs

jsx

I have have a large application that monitors a file called routes.js . I can not change the file name or mess with routes.js at all. I need to load another file based on a useState variable from another component when a condition is met. This following code will need to be put in Apps.js example:

if (!change) {
import routes from "routes";
} else {
import routes from "newroutes"
}

Is this possible?

like image 903
Raphael Heard Avatar asked Mar 29 '26 16:03

Raphael Heard


1 Answers

You can just alias the imports.

import routes_1 from "routes";
import routes_2 from "newroutes"  

Then, you can just declare a variable: routes and assign the appropriate value to it.

routes = !change ? routes_1 : routes_2;
like image 172
Ergis Avatar answered Mar 31 '26 05:03

Ergis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!