1

I've come across a problem in my React app where a certain component requires a stylesheet to be loaded dynamically (when the component is mounted, it's loaded; when it's unmounted, it's removed from the page).

To my surprise, I can't seem to find anything about dynamically loaded stylesheets online or within the official React documentation at all. The closest thing I found to a solution was this answer from 2017, and while this solution works for mounting the component, it doesn't remove the stylesheet once it has been unmounted.

There are always workarounds such as appending to a stylesheet from my CDN in the head once the component is mounted, but I want to keep as much css in one directory as I can.

The ideal solutions would be something along the lines of:

class Parent extends React.Component{
    render(){
        return <div></div>;
    }
}
export default withStyles(Parent, [pathToStylesheet]);

// or... 
class Parent extends React.Component{
    componentDidMount(){ import(pathToCss); }
    componentWillUnmount(){ removeImport(pathToCss); }
    
    render(){
        return <div></div>;
    }

}

All help is appreciated, cheers.

GROVER.
  • 4,071
  • 2
  • 19
  • 66

1 Answers1

1
import React, { Component } from "react";
import styleAsString from '!!raw-loader!../styles/MyComponent.css';

class MyComponent extends Component {
    componentDidMount() {
        this.addStyle(styleAsString);
    }

    componentWillUnmount() {
        if(this.style) {
            document.head.removeChild(this.style);
        }
    }

    addStyle = (content) => {
        const style = document.createElement("style");
        style.type= "text/css";
        style.innerHTML = content;

        this.style = document.head.appendChild(style);
    };

    render() {
        return <div> textInComponent </div>;
    }
}

Import css file as string, load & unload css style manually; Just an idea, not tested!

gu mingfeng
  • 1,010
  • 8
  • 10