Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 718
Nur L Avatar asked Jul 26 '20 21:07

Nur L


People also ask

How do you style children in React?

Use React API cloneElement() type, props, children) , so basically we can't change anything of it. By cloneElement() , we can recreate the children with new props. To change the style, we can pass in a style prop into the image and also we can add an onClick handler to change the gallery state.

Which form is correct to style an element in React component?

Props can be used to style styled components in the same way that they are passed to normal React components. Props are used instead of classes in CSS and set the properties dynamically.


2 Answers

Very simple, use all: unset

.react-root {
  all: unset;
}
like image 50
Mordechai Avatar answered Oct 19 '22 08:10

Mordechai


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.

like image 2
Nico Co Avatar answered Oct 19 '22 09:10

Nico Co