Embedded React + JSS component: how to protect generic elements like <button>, <p> from getting including page's style?

Viewed 182

I have a React component that is embedded in other webpages (i.e. through an extension or as a third-party embedded tool).

Most of its style classes are creates using JSS, and these get unique class names which can't be overridden by the including page.

However, some of our elements are generic ones (e.g. <p>, <button>, <h1>, <h2>, etc.) that we must use for accessibility reasons (e.g. screen readers require <hX> hierarchical headings, and it is hard to avoid using buttons). These elements' styles are often overridden by the including page's style, if this page uses element selectors for these elements.

I tried encapsulating the React component using a Shadow DOM but it seems non-trivial, mainly because it seems to prevent React from operating correctly (click events aren't being passed, etc.). react-shadow (https://github.com/Wildhoney/ReactShadow) doesn't seem to work either.

Is there a way to protect these elements' style from being overridden?

3 Answers

Very simple, use all: unset

.react-root {
  all: unset;
}

You can try adding an additional class to all of the HTML elements outside of your React component. Start your component's code with this and after that proceed with your current work.

First you need to make a list of all the document's elements:

var allElements = document.querySelectorAll( '*' );

Then add the new class to all those elements:

for (var i = 0; i < allElements.length; i++) {
    allElements[i].classList.add('newclassName');
}

Now all elements from the page where your React component will be embedded should have an additional class that will stop your styles to override the original ones.

I have the same problem here. Our React application is wrapped with another web framework, so, this framework has its own styles for HMTL tags. Our solution was doing a reset CSS inside React.

We copy all styles from the other framework and create our Reset CSS based on this file. All tags and all CSS pseudo-classes related to tags.

We find no other way to do this.

Related