How to use material-ui (alpha) with styeld-components properly? - reactjs

I've been trying to use styled-components with the alpha version of material-ui
According to the documentation, this should work out of the box.
This code:
const StyledButton = styled(Button)`
color: red;
text-transform: uppercase;
`;
return <StyledButton>Button</StyledButton>;
will generate something like this:
<button tabindex="0" class="MuiButtonBase-root-3177716317 sc-bdVaJa sxRGN" type="button" role="button">
...
</button>
It looks good.
However, the only problem I have is the order of the injected CSS styles (pic). Styles from styled-components are injected before MUI's styles which make their priority lower.
Is there any way to solve this without using !important?

In the current release (i.e. non-alpha) version, what you've asked would indeed require !important basis:
"Note that CSS properties defined inline are given priority over those defined in a CSS class. You need to use !important to take precedence over the inline style."
Ref: http://www.material-ui.com/#/customization/styles
Perhaps the alpha hasn't quite moved away from this inline requirement yet or it is still a work-in-progress.
What I've done to overcome this sort of thing myself is to (unfortunately) recreate the entire CSS on a standard <button> element when I need such a solution. Here's an example of how I'm doing that with a react-photonkit "theme"
// #flow
import styled from 'styled-components';
const PhotonStyledButton = styled.button`
font-family: Arial, Roboto, Helvetica, sans-serif;
height: 30px;
display: inline-block;
padding: 6px 12px;
margin-bottom: 0;
font-size: 12px !important;
line-height: 1.4;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: default;
background-image: none;
border: 1px solid transparent;
border-radius: $default-border-radius;
box-shadow: 0 1px 1px rgba(0,0,0,.06);
-webkit-app-region: no-drag;
&:focus {
outline: none;
box-shadow: none;
}
color: #333;
border-top-color: #c2c0c2;
border-right-color: #c2c0c2;
border-bottom-color: #a19fa1;
border-left-color: #c2c0c2;
background-color: #fcfcfc;
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fcfcfc), color-stop(100%,#f1f1f1));
background-image: -webkit-linear-gradient(top, #fcfcfc 0%, #f1f1f1 100%);
background-image: linear-gradient(to bottom, #fcfcfc 0%, #f1f1f1 100%);
&:active {
background-color: #ddd;
background-image: none;
}
`;
export default PhotonStyledButton;

styled-components in general is compatible with any component library. When you write styled(AnotherComponent) we take that component and inject an automatically generated class name. This means essentially it's the same thing as writing <AnotherComponent className="sc-asdf123" />!
The current version of material-ui specifically is a bit difficult to custom style because it uses inline styles. From the MaterialUI documentation:
Note that CSS properties defined inline are given priority over those defined in a CSS class. You need to use !important to take precedence over the inline style.
This means simply using styled(MaterialButton) won't work as the passed-in styles will mostly just be ignored. You need to bump the specificity of your styles to override the inline styles that material-ui ships with. (this article is a great primer on specificity if you're not familiar with the details)
Answer for the alpha version of material-ui
The current alpha version of material-ui has switched to using JSS under the hood. (which is CSS in JS not inline styles, like styled-components) This means the issue is likely to be that the styled-components styles are injected after the default material-ui styles. (which are injected by JSS)
JSS supports custom injection points so you might be able to add a <!-- jss --> comment to the HEAD of your HTML to make sure JSS injects its CSS before the styled-components injected CSS?
Answer for the current version of material-ui
There are two ways to bump the specificity of the styled-components injected styles, one more tedious and one a bit more "hacky". The first one is adding !important at the end of all of your styles:
const Button = styled(MaterialButton)`
color: blue!important;
`
While this works in most cases it gets tedious very fast when you have lots of custom styling in a component. The better way is to use the class name hack:
const Button = styled(MaterialButton)`
&&& {
color: blue;
}
`
These ampersands get replaced with the automatically generated class name meaning the outputted CSS looks something like this:
.sc-asdf123.sc-asdf123.sc-asdf123 {
color: blue;
}
This bumps specificity by a big margin, thusly overriding the defined inline styles, and is less annoying than having to put !important after each rule.

Now we can use <!-- material-ui --> to make sure the styles are injected after it.
By default, Material-UI will look for a html comment named to inject styles after. By adjusting the placement of this comment within your HTML body you can control the order that CSS rules are applied to your components. (ref)

Related

Overwriting MUI with scss

I'm working on a React project that uses MUI and Sass. Currently there are multiple scss-files full of !important to overwrite the MUI styles with sass. I tried to fix this by removing the !important's and adding:
import { StyledEngineProvider } from '#mui/material/styles';
import CssBaseline from '#mui/material/CssBaseline'
<CssBaseline />
<StyledEngineProvider injectFirst>
*** component tree here ***
</StyledEngineProvider>
as suggested here: Issue with #Mui and modularized scss competing intermittently. How to consistently override #mui default styling with scss modules?
Which seemed to work at first but stops working when you focus on a component. For example this button turns white with a blue border when hovered over:
scss
.button {
width: 250px;
height: 50px;
border: 1px solid grey;
border-radius: 15px;
text-transform: none;
}
.go-button {
#extend .button;
background-color: grey;
color: whitesmoke;
}
reactjs
<Button
className="go-button"
variant="outlined"
onClick={handleClick}
>
Go
</Button>
We are not using modules or makeStyles. What would be the best way to overwrite MUI without the !important's?
The default styles for many MUI components will include some styles for specific states like :hover, .Mui-focused that have a higher specificity than the styles of the default state. When overriding those styles you need to use the same specificity.
For instance, Button has default styles specific to hover, so you will need to specify style overrides for the hover state.
For example, here's one possible way to define your button styles:
.button {
width: 250px;
height: 50px;
border: 1px solid grey;
border-radius: 15px;
text-transform: none;
}
.go-button {
#extend .button;
background-color: grey;
color: whitesmoke;
}
.go-button:hover {
#extend .go-button;
background-color: #999;
}
According to my knowledge experience, you must use styled-components with MUI because they have a better pair rather then SCSS, with better pair you have better performance of the website & with styled-components you can easily modify the changes of MUI.
Visit this link for advanced usage

How to apply custom styling on react-datepicker with css modules?

I am trying to apply custom styling on react-datepicker datepicker input. Using modules:
.custom-input {
border-radius: 10px !important;
padding: 5px 10px 5px 30px !important;
border: 2px solid #cccccc !important;
font-size: 16px !important;
line-height: 26px !important;
}
And then I add the className to the datepicker:
<DatePicker
className={s["custom-input"]}/>
I created codesandbox here:
https://codesandbox.io/s/clnd-datepicker-forked-h9ju59
Any idea why its not working, even with !important on?
[EDIT]
Codesandbox is fixed.
Hello Alex : I took the code to my local vs code and updated the code a little bit which worked:
The only difference I code see here is instead of using s[""] you can use like :
import styles or <any name you would like to call it> from "./Datepicker.module.css"
and then call the css class name in the code like:
className ={styles.<cssClassName>}.
See my code ss:
PS: I also found one strange thing about codesandbox is that it keeps complaining about .module.css file in typescript code file. hence my codesandbox that I sent earlier wasn't working well.

Extension styling breaks after being published [duplicate]

I wrote a Google Chrome extension, which popups a dialog with an autocomplete field and it's own style, but there are some sites where my CSS gets totally broken, which doesn't look very nice.
I know about isolating styles with iFrames, but in Google Chrome extension there is no way to isolate my HTML and CSS in this way. Another method is to wrap all my stuff into a separated div with it's own id and relative styles for that id, and I do so, but it seems that it doesn't work on some sites with "hard" tags style overloading or "!important" directives in the CSS code.
So, I want to know is there any way to really isolate my styles in z convenient way or it's my bad carma to overload every little CSS property to fix one or another style issue for each site?
By the way: I set up my manifest to load all the things at the "document_end", but I see it's not being applied to the stylesheets which is every time loaded whenever the DOM is ready.
At the time of asking the question, your only option was to either use iframes, or stylesheets with a very high specificity and explicitly set all properties that might affect styles. The last method is very cumbersome, because there will always be some property that is overlooked by you. Consequently, the only usable method for isolating stylesheets was to use iframes.
The solution to this problem -isolation of styles without iframes- is Shadow DOM (since Chrome 25). You can find a tutorial at HTML5 Rocks. For a real-world Chrome extension that uses Shadow DOM to isolate styles, see Display #Anchors (source code here).
As I've recently gone through the gauntlet of this issue, I want to share some information I think is valuable.
First, Rob W's answer is correct. Shadow DOM is the correct solution to this problem. However, in my case not only did I need CSS isolation, I also needed JavaScript events. For example, what happens if the user clicks a button that lives within the isolated HTML? This gets really ugly with just Shadow DOM, but we have another Web Components technology, Custom Elements, to the rescue. Except that as of this writing there is a bug in chrome that prevents custom element in chrome extensions. See my questions here and here and the bug here.
So where does that leave us? I believe the best solution today is IFrames, which is what I went with. The article shahalpk linked is great but it only describes part of the process. Here's how I did it:
First, create an html file and js file for your isolated widget. Everything inside these files will run in an isolated environment in an iframe. Be sure to source your js file from the html file.
//iframe.js
var button = document.querySelector('.my-button');
button.addEventListener('click', function() {
// do useful things
});
//iframe.html
<style>
/* css */
</style>
<button class='my-button'>Hi there</button>
<script src='iframe.js'></script>
Next, inside your content script create an iframe element in javascript. You need to do it in javascript because you have to use chrome.extension.getURL in order to grab your iframe html file:
var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("iframe.html");
document.body.appendChild(iframe);
And that's it.
One thing to keep in mind: If you need to communicated between the iframe and the rest of the content script, you need to chrome.runtime.sendMessage() to the background page, and then chrome.tabs.sendMessage from the background page back to the tab. They can't communicate directly.
EDIT: I wrote a blog post detailing everything I learned through my process, including a complete example chrome extension and lots of links to different information:
https://apitman.com/3/#chrome-extension-content-script-stylesheet-isolation
In case my blog goes down, here's the sources to the original post:
Blog post
Example source
Either use all
.some-selector {
all: initial;
}
.some-selector * {
all: unset;
}
or use Shadow DOM
Library
function Widget(nodeName, appendTo){
this.outer = document.createElement(nodeName || 'DIV');
this.outer.className = 'extension-widget-' + chrome.runtime.id;
this.inner = this.outer.createShadowRoot();
(appendTo || document.body).appendChild(this.outer);
}
Widget.prototype.show = function(){
this.outer.style.display = 'block';
return this;
};
Widget.prototype.hide = function(){
this.outer.style.display = 'none';
return this;
};
Usage
var myWidget = new Widget();
myWidget.inner.innerHTML = '<h1>myWidget</h1>';
You can access the widget contents via myWidget.inner and the outer via myWidget.outer.
Styles
/*
* Reset Widget Wrapper Element
*/
.extension-widget-__MSG_##extension_id__ {
background: none;
border: none;
bottom: auto;
box-shadow: none;
color: black;
cursor: auto;
display: inline;
float: none;
font-family : "Helvetica Neue", "Helvetica", "Arial", sans-serif;
font-size: inherit;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: auto;
left: auto;
letter-spacing: 0;
line-height: 100%;
margin: 0;
max-height: none;
max-width: none;
min-height: 0;
min-width: 0;
opacity: 1;
padding: 0;
position: static;
right: auto;
text-align: left;
text-decoration: none;
text-indent: 0;
text-shadow: none;
text-transform: none;
top: auto;
vertical-align: baseline;
white-space: normal;
width: auto;
z-index: 2147483648;
}
/*
* Add your own styles here
* but always prefix them with:
*
* .extension-widget-__MSG_##extension_id__
*
*/
.extension-widget-__MSG_##extension_id__{
position: fixed;
top: 100px;
margin: 0 auto;
left: 0;
right: 0;
width: 500px;
}
.extension-widget-__MSG_##extension_id__::shadow h1 {
display: block;
margin: 0 auto;
padding: 20px;
background-color: yellow;
border: 10px solid green;
font-size: 20px;
text-align: center;
}
I recently created Boundary, a CSS+JS library to solve problems just like this. Boundary creates elements that are completely separate from the existing webpage's CSS.
Take creating a dialog for example. After installing Boundary, you can do this in your content script
var dialog = Boundary.createBox("yourDialogID", "yourDialogClassName");
Boundary.loadBoxCSS("#yourDialogID", "style-for-elems-in-dialog.css");
Boundary.appendToBox(
"#yourDialogID",
"<button id='submit_button'>submit</button>"
);
Boundary.find("#submit_button").click(function() {
// some js after button is clicked.
});
Elements within #yourDialogID will not be affected by the existing webpage. And find() function returns a regular jQuery DOM element so you can do whatever you want with it.
Hope this helps. Please let me know if you have any question.
https://github.com/liviavinci/Boundary
Use iframes. It's a workaround, but works fine.
Maxime has written an article on it.

How to prevent webpage styling getting affected by inject chrome extension's styling [duplicate]

I wrote a Google Chrome extension, which popups a dialog with an autocomplete field and it's own style, but there are some sites where my CSS gets totally broken, which doesn't look very nice.
I know about isolating styles with iFrames, but in Google Chrome extension there is no way to isolate my HTML and CSS in this way. Another method is to wrap all my stuff into a separated div with it's own id and relative styles for that id, and I do so, but it seems that it doesn't work on some sites with "hard" tags style overloading or "!important" directives in the CSS code.
So, I want to know is there any way to really isolate my styles in z convenient way or it's my bad carma to overload every little CSS property to fix one or another style issue for each site?
By the way: I set up my manifest to load all the things at the "document_end", but I see it's not being applied to the stylesheets which is every time loaded whenever the DOM is ready.
At the time of asking the question, your only option was to either use iframes, or stylesheets with a very high specificity and explicitly set all properties that might affect styles. The last method is very cumbersome, because there will always be some property that is overlooked by you. Consequently, the only usable method for isolating stylesheets was to use iframes.
The solution to this problem -isolation of styles without iframes- is Shadow DOM (since Chrome 25). You can find a tutorial at HTML5 Rocks. For a real-world Chrome extension that uses Shadow DOM to isolate styles, see Display #Anchors (source code here).
As I've recently gone through the gauntlet of this issue, I want to share some information I think is valuable.
First, Rob W's answer is correct. Shadow DOM is the correct solution to this problem. However, in my case not only did I need CSS isolation, I also needed JavaScript events. For example, what happens if the user clicks a button that lives within the isolated HTML? This gets really ugly with just Shadow DOM, but we have another Web Components technology, Custom Elements, to the rescue. Except that as of this writing there is a bug in chrome that prevents custom element in chrome extensions. See my questions here and here and the bug here.
So where does that leave us? I believe the best solution today is IFrames, which is what I went with. The article shahalpk linked is great but it only describes part of the process. Here's how I did it:
First, create an html file and js file for your isolated widget. Everything inside these files will run in an isolated environment in an iframe. Be sure to source your js file from the html file.
//iframe.js
var button = document.querySelector('.my-button');
button.addEventListener('click', function() {
// do useful things
});
//iframe.html
<style>
/* css */
</style>
<button class='my-button'>Hi there</button>
<script src='iframe.js'></script>
Next, inside your content script create an iframe element in javascript. You need to do it in javascript because you have to use chrome.extension.getURL in order to grab your iframe html file:
var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("iframe.html");
document.body.appendChild(iframe);
And that's it.
One thing to keep in mind: If you need to communicated between the iframe and the rest of the content script, you need to chrome.runtime.sendMessage() to the background page, and then chrome.tabs.sendMessage from the background page back to the tab. They can't communicate directly.
EDIT: I wrote a blog post detailing everything I learned through my process, including a complete example chrome extension and lots of links to different information:
https://apitman.com/3/#chrome-extension-content-script-stylesheet-isolation
In case my blog goes down, here's the sources to the original post:
Blog post
Example source
Either use all
.some-selector {
all: initial;
}
.some-selector * {
all: unset;
}
or use Shadow DOM
Library
function Widget(nodeName, appendTo){
this.outer = document.createElement(nodeName || 'DIV');
this.outer.className = 'extension-widget-' + chrome.runtime.id;
this.inner = this.outer.createShadowRoot();
(appendTo || document.body).appendChild(this.outer);
}
Widget.prototype.show = function(){
this.outer.style.display = 'block';
return this;
};
Widget.prototype.hide = function(){
this.outer.style.display = 'none';
return this;
};
Usage
var myWidget = new Widget();
myWidget.inner.innerHTML = '<h1>myWidget</h1>';
You can access the widget contents via myWidget.inner and the outer via myWidget.outer.
Styles
/*
* Reset Widget Wrapper Element
*/
.extension-widget-__MSG_##extension_id__ {
background: none;
border: none;
bottom: auto;
box-shadow: none;
color: black;
cursor: auto;
display: inline;
float: none;
font-family : "Helvetica Neue", "Helvetica", "Arial", sans-serif;
font-size: inherit;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: auto;
left: auto;
letter-spacing: 0;
line-height: 100%;
margin: 0;
max-height: none;
max-width: none;
min-height: 0;
min-width: 0;
opacity: 1;
padding: 0;
position: static;
right: auto;
text-align: left;
text-decoration: none;
text-indent: 0;
text-shadow: none;
text-transform: none;
top: auto;
vertical-align: baseline;
white-space: normal;
width: auto;
z-index: 2147483648;
}
/*
* Add your own styles here
* but always prefix them with:
*
* .extension-widget-__MSG_##extension_id__
*
*/
.extension-widget-__MSG_##extension_id__{
position: fixed;
top: 100px;
margin: 0 auto;
left: 0;
right: 0;
width: 500px;
}
.extension-widget-__MSG_##extension_id__::shadow h1 {
display: block;
margin: 0 auto;
padding: 20px;
background-color: yellow;
border: 10px solid green;
font-size: 20px;
text-align: center;
}
I recently created Boundary, a CSS+JS library to solve problems just like this. Boundary creates elements that are completely separate from the existing webpage's CSS.
Take creating a dialog for example. After installing Boundary, you can do this in your content script
var dialog = Boundary.createBox("yourDialogID", "yourDialogClassName");
Boundary.loadBoxCSS("#yourDialogID", "style-for-elems-in-dialog.css");
Boundary.appendToBox(
"#yourDialogID",
"<button id='submit_button'>submit</button>"
);
Boundary.find("#submit_button").click(function() {
// some js after button is clicked.
});
Elements within #yourDialogID will not be affected by the existing webpage. And find() function returns a regular jQuery DOM element so you can do whatever you want with it.
Hope this helps. Please let me know if you have any question.
https://github.com/liviavinci/Boundary
Use iframes. It's a workaround, but works fine.
Maxime has written an article on it.

Reusing existing CSS in styled-component

We've a large project that exist of multiple styled components.
But for a next release and design update of that component we'll working together with a new partner that will deliver the styleguide and a CSS file that they are created for our client.
So I'm looking how I can re-use the styles of our partner in a styled component.
Do you think it's a good idea to do something like:
const PrimaryButton = styled(".btn-primary)``.
Instead of:
const PrimaryButton = styled.button``;
Actually, I can not find any working example, thus I think it's not possible... So, does someone know how I can do something like this?
Ehm, and for some reason I want to avoid to have something like this...
<PrimaryButton className="btn-primary"></PrimaryButton>
You can reuse styled components by extending the styles.
const Button = styled.button`
color: palevioletred;
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
// A new component based on Button, but with some override styles
const PrimaryButton = styled(Button)`
color: blue;
border-color: blue;
`;

Resources