Search code examples
reactjsvite

Scope CSS with React + Vite


I am new to react and have researched a lot but I couldn't find a solution for my specific problem. I have a 20'000 line long CSS and a long HTML file from someone else. I have to display it on my website (I can't use an iframe due to technical reasons). So I created a react component that returns the HTML and I imported the CSS file, which is now messing up the style of the rest of the website.

How can I scope the CSS to only be applied to that component? As the file is so long, I can't just add more specific classes to every CSS selector. Obviously, I can't use inline styles and I also can't use modules because not everything in that CSS file is under a specific class. For example, there is this in the CSS: input[type="text"]{...} (without a class or id that would differentiate between my own text inputs).

Am I missing something?


Solution

  • Edit: now that CSS nesting seems well supported, you may not even need to use SCSS.


    Since you can't edit every single selector in the file, the easiest solution is to convert your CSS file into SCSS, and then to nest all of the code into a scoped class/id that you can use on your component:

    MyComponent.jsx

    import "./styles.scss";
    
    const MyComponent = () => (
      <div id="scoped">
        {/* ... */}
      </div>
    );
    
    export default MyComponent;
    

    styles.scss

    #scoped {
      // CSS here
    }
    

    SCSS supports CSS syntax (unlike SASS), so you shouldn't need to make any further changes to the original code. However, this will not work for selector such as html, since you're supposed to have that at the root of your app.

    You will need to install sass on your app to make it work with Vite:

    npm add -D sass