Import a CSS dynamically in React

In React you can import a .css file dynamically depending on a variable.

Example:

jsx
import React, { useEffect } from 'react';

const DynamicStyle = () => {
    
    useEffect(() => {
        
        // Declaring new date
        let date = new Date();
        
        // Defining morning and afternoon hours
        let morning = date.getHours() <  12;
        
        // Importing files depending on time of the day
        if(morning) import (`../Styles/morning.css`);
        else        import (`../Styles/afternoon.css`);
        
    }, []);
    
    return(
        <p>This is a dynamic component.</p>
    );
    
}

export default DynamicStyle;

This will be morning.css:

CSS
p{
    background: white;
    color: black;
}

And this will be afternoon.css:

CSS
p{
    background: black;
    color: white;
}

Note

The previous example will work if you need to import a .css one time, but if you need to swap between 2 files, it won't. Bear in mind that you can't unmount imported .css files.

Example:

jsx
import React, { useEffect, useState } from 'react';

const DynamicStyle = () => {
    
    const [style, setStyle] = useState('morning');
    
    const changeTheme = () => {
        
        // ❌ This won't work because after 2 clicks
        // ❌ Both morning.css and afternoon.css will be imported
        // ❌ And the css variables may overlap
        if(style === 'afternoon') {
            
            import (`../Styles/morning.css`);
            setStyle('morning');
            
        }
        else{
            
            import (`../Styles/afternoon.css`);
            setStyle('afternoon');
            
        }
        
    }
    
    return(
        <button onClick = {changeTheme}>
            Click me
        </button>
    );
    
}

export default DynamicStyle;

If you need to swap between .css files, it's better to use a single .css with variables as properties.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.