Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude global styles in a React App?

I am using Material UI for building my React Project.

However there is a component which has to be embedded to a different site. Meaning, I am providing the production build of this component to embed it to a different site.

My React app's css is getting overridden by the global styles defined in that website.

I don't want this behaviour. Is there any way I can isolate the css of my react app and the global css of the other website.

I saw this question but the solutions didn't help me.

like image 553
Shahrukh Mohammad Avatar asked Mar 04 '23 13:03

Shahrukh Mohammad


1 Answers

If iframes and Web Components are out of the question, the only remaining option is CSS resets.

Create a CSS class and a series of rules that reset the styles of any elements that occur inside that class.

.my-reset {
  /* Global resets (e.g. font family) */
}

.my-reset p {
  /* Reset paragraph styles */
}

.my-reset label {
  /* Reset label styles */
}

/* etc. */

Apply that class to the root-level component:

function MyApp() {
    <div className="my-reset">
        { /* app goes here */ }
    </div>
}

There are plenty of CSS reset libraries out there. Since you have no control over global styles, you're going to have to be heavy handed with the resets. So if it's at all possible, make your component embeddable as an iframe.

like image 87
Steve Avatar answered Mar 16 '23 13:03

Steve