React Conditional Import / Conditional CSS Import

Prawira G.
2 min readJun 2, 2020

A react conditional import, especially useful for conditional CSS import.

PROBLEM

Have you ever tried to conditionally import React components or CSS file? The first instinct you have is to do a conditional import using if-else.

Soon… you will find yourself in trouble because your react will not bundled with the error message Parsing error: ‘import' and ‘export' may only appear at the top level in the terminal.

Then… you start googling and changing the word import to require. And you think it works.

However, the require method only worked in development (or during the react bundling if you use react script to build). Thus, your code may not work in the production version.

React Conditional CSS Import

SOLUTION

We can solve this problem using React.Lazy and React.Suspense.

The React.lazy method is introduced for code-splitting so that conditional import is possible and this will reduce the load-time for bundled JavaScript file as to improve…

--

--

Prawira G.

Full Stack TypeScript | Blockchain Enthusiast | OAUTH2.0 & OIDC | Software Engineer.