styled-components - Parent component style overriding child style - css

I'm using styled-components with React. I'd like to remove the default bottom margin for all <p>s, so in my main App component I added a nested selector:
const App = styled.div`
p {
margin: 0;
}
`
However, I do want to be able to add margin to some <p>s, e.g.:
const SpacedP = styled.p`
margin-bottom: 10px;
`
But when I try to use a <SpacedP> within <App>, the resulting App CSS is more specific than the SpacedP CSS, so my <SpacedP>s still have no margin! (App CSS compiles to ${App} p { ... }, while SpacedP only has one prefix, ${SpacedP} { ... }).
Is there a common pattern for situations like these? I don't really like the &&& specificity workaround suggested here, seems ugly and hacky; hoping there's a more common setup that I'm missing.
Thanks!

Related

NextJS: Modify third-party component CSS in different pages

With third-party components, the way to include their styles is by importing their stylesheet into _app.tsx or importing the stylesheet into your component that uses the third-party component, as described here: https://nextjs.org/docs/basic-features/built-in-css-support#import-styles-from-node_modules or by adding to next.config.js like so:
// next.config.js
const withTM = require("next-transpile-modules")([
"#fullcalendar/common",
"#fullcalendar/daygrid",
"#fullcalendar/timegrid",
"#fullcalendar/interaction",
"#fullcalendar/react",
"#fullcalendar/list",
To modify the third-party stylesheet, you need to create your own stylesheet and add it to _app.tsx; those modifications might look like this:
// styles/modified-fullcalendar.scss
.fc-col-header {
width: 100% !important;
}
Another option, at least for my use case (Full Calendar) is to use CSS variables as described here in technique 2 on this page: https://fullcalendar.io/docs/css-customization. There was a lengthy thread about this on the Full Calendar issues page, as seen here: https://github.com/fullcalendar/fullcalendar/issues/5393
The problem with all of these methods of customization is that they're global, and so anywhere you use this third-party component it'll look the same. However, in my case, I want to use the component on two different pages, with different styling modifications. With most frameworks, I would simply import the relevant modified stylesheet wherever I needed it, but NextJS doesn't allow that. How can I achieve the modifications I want?
The solution is to wrap the component in a div with a specific class name, then do the css overrides in a nested format for each use case in the override file.
Explanation:
Say your third-party component is FullCalendar. It's being imported and used in the files Foo.tsx and Bar.tsx. In Foo, let's say you want the calendar cells to be green.
To make the modification, you create the file modified-fc.scss and do the following:
// modified-fc.scss
.fc-cell {
background: green !important;
}
You then import modified-fc.scss into _app.tsx in order to apply the styles globally, and you're done. However, this prevents you from changing the cell color to orange in Bar. To circumvent this, just wrap the component:
// Foo.tsx
<div className=".wrapper1">
<FullCalendar/>
</div>
// Bar.tsx
<div className=".wrapper2">
<FullCalendar/>
</div>
and then nest the classes:
// modified-fc.scss
.wrapper1 {
.fc-cell {
background: green !important;
}
}
.wrapper2 {
.fc-cell {
background: orange !important;
}
}
OR
.wrapper1 > .fc-cell {
background: green !important;
}
.wrapper2 > .fc-cell {
background: orange !important;
}

How to create shared styles using styled components?

I am trying to achieve something like the following output using styled components (shared selectors).
.styleOne, .styleTwo {
color: blue; /* shared */
}
.styleOne {
font-size: 10px;
}
.styleTwo {
font-size: 20px;
}
I've tried:
1 - (this one makes sense why it doesn't render my desired output)
const shared = `color: blue;`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
2 -
const Shared = styled.div`
color: blue;
`
const StyleOne = styled(Shared)`
font-size: 10px;
`
const StyleTwo = styled(Shared)`
font-size: 20px;
`
3 -
const shared = css`
color: blue;
`
const StyleOne = styled.div`
font-size: 10px;
${shared}
`
const StyleTwo = styled.div`
font-size: 20px;
${shared}
`
All the above result in something like the following:
.styleOne {
color: blue; /* duplicated */
font-size: 10px;
}
.styleTwo {
color: blue; /* duplicated */
font-size: 20px;
}
Technically the styles are shared in each approach from a code perspective. However, the rules are still duplicated. I was hoping to be able to share the CSS rules themselves.
An analogy in SASS would be - I want to use a placeholder instead of a mixin.
To add some context on why I want to achieve this, I want to have a smaller HTML document for performance reasons. I'm imagining in a large app where I'm sharing a lot of styles, the style block may get huge.
The term large apps is too ambiguous to state whether or not you'll have performance issues -- whether it's from downloading/executing JS or downloading parsing CSS and/or fetching other media (fonts, images, etc). That said, styled-components applies styles in the head during run-time and does an excellent job of deferring them until they're required in the DOM.
Take a look at this example and follow these steps:
Inspect the DOM and within the Elements tab expand the head
Look for this style tag and expand it: <style data-styled="active" data-styled-version="5.2.0"></style>
With the inspector still open, navigate to other pages and notice how class names are generated on-the-fly
Once the classes have been assigned, they're then reused
This has the similar effect of using css-modules (scoped classes) without the extra request to download the required CSS, and it automatically prefixes CSS properties without any additional plugins.
So the question becomes: Is it better to have more Javascript (packaging and running styled-components in run-time) and less CSS (less requests to download CSS per page) or more CSS and potentially less Javascript? You'll need to run metrics -- like a lighthouse test -- in production to determine which is more performant; otherwise, it's just going to be a guess/personal opinion.
Either way, you're going to be running into some sort of render blocking, whether it's downloading/parsing CSS or downloading/executing JS.

Pierce component style globally

I need to pierce the styles of my component from the global styles.scss file.
Basically, I've used mat-card component wrapped in a custom-component. In
some cases, I want to change styles to the mat-card when a custom-component is preceded by another custom-component
The idea would be:
global-styles.scss
custom-component ~ custom-component::ng-deep {
.mat-card {
background-color: red;
}
}
The host-context seemed like a good idea, I tried it this way
custom-component.scss
// does not work
host-context(~custom-component) { background-color: red; }
I've tried this and some other combinations, but they don't seem to work. How are we supposed to use the >, ~, + selectors to style angular components?.
Cheers
Personally I avoid piercing selectors at all costs. It breaks the entire component model, and tightly couples code.
I would approach this in a slightly different way. I would have my custom-component have an optional Input() embedded = false
Your usage could be as follows:
// top level
<custom-component></custom-component>
// nested level
<custom-component [embedded]="true"></custom-component>
Then use ngClass with the embedded property to trigger the color change.
See docs for more info on ngClass
https://angular.io/api/common/NgClass
Ok not a solution for this, but there's one thing to consider.
If you want to apply styles to your component using the selector your-component, you have to set display: block; property in your component :host. I totally missed this, but it would look like this:
your-component.css
:host {
display: block;
}
your parent component css
your-component ~ your-component {
margin-top: 15px;
}
And it works. My problem was originally related to that.

Applying CSS stylesheet only to active component

I'm working on a ReactJS app that has a header at the top, a menu on the left, and the "frame" in the middle is where routes and their corresponding components are loaded. I want to be able to apply a CSS stylesheet to specific components only when they are loaded. I also don't want them applied all the time or to the top header or left menu.
My expectation was that adding import 'custom.css'; to a specific component would only apply the stylesheet's styles to that component and it's children when the route is active. Instead, it applies it to the entire page even when the route/component are not loaded.
I understand that an alternative approach is styled components, but, for my use-case, a design company is supplying a stylesheet (which should remain unchanged) that we need to consume only for the sub-module I'm working on and I don't want its styles to affect the rest of the app.
How can I have a stylesheet only applied to my active route/component?
Use simple CSS technique. Suppose you have two components with different css files (say about.css and contact.css). Now consider your both CSS file have one common class with different style properties, like:
about.css
.container{
max-width: 400px;
}
contact.css
.container{
max-width: 500px;
}
Yes in ReactJS both the CSS files will load at the same time and will override any one of the style. so to solve this problem add class to differentiate this styles, like:
about.css
.about-component.container{
max-width: 400px;
}
contact.css
.contact-component.container{
max-width: 500px;
}
If you want apply only when the component is mounted, you can use the lifecycle.
The follow example is based in the idea you are using sass, React, sass-node and have the loaders into webpack.
<pre>
import React from 'react';
import './styles.scss';
class MyComponent {
constructor(props) {
super(props);
this.state = { className: '' }
}
componentDidMount() {
this.setState({
className: 'myOwnClass'
});
}
render(){
return (
<div className={this.state.className}>This is a example</div>
);
}
}
export default myComponent;
</pre>
To be able to only call that specific CSS when you need it you can use CSS Modules. You may need to update your version of react.
When saving your CSS file save it with a ".module.css" eg. "styles.module.css". The CSS in these files can only be used and accessed by hte components where are they are imported. As stated in a tutorial from W3Schools.
Let's say this is your CSS code in styles.module.css:
.container {
color: white;
}
.cont-child {
background-color: red;
}
Then in your JS file you can import the CSS file like this if the JS and CSS files are in the same directory. Make sure you point to the correct path.
import styles from './styles.module.css'
Then in your HTML section you can use it like this:
class Home extends React.Component {
render() {
return(
<main className={ styles.container } >
<div className={ styles["cont-child"]} >
Some div text about something...
</div>
</main>
);
}
}
I currently use both ways to access the selectors, since the styles variable acts like an object. I placed both of them here because the second option is capable of fetching selectors named like "btn-active". Which comes in handy in some situations. Camelcasing is considered cleaner though.
Please note: I originally posted this answer as a reply to a similar question here React CSS - how to apply CSS to specific pages only
I want to be able to apply a CSS stylesheet to specific components
only when they are loaded.
Why not apply the styles inline via React.js?
Step 1. Create the style object for the component:
var componentOneStyle = {
color: 'white',
backgroundColor: 'red'
};
Step 2. Populate the component's style attribute with the style object:
ReactDOM.render(<div style={componentOneStyle}>This is Component One</div>, mountNode);

What does :global (colon global) do?

In some SCSS files, I see the following:
:global {
/* ... */
}
I don't know if it is an SCSS feature or a CSS feature.
I tried searching about it but couldn't find any good results at first sight.
The :global operator is used in CSS Modules. Modular CSS uses a CSS Modules compiler to scope CSS styles within their respective modules (e.g., React component).
Here's an example from a React module (in the file ErrorMessaging.less for the ErrorMessaging.jsx React component):
:global(.ocssContainer) {
.ui_column {
padding-left: 0;
}
}
This gets compiled into:
.ErrorMessaging__alertContainer--1I-Cz .ocssContainer .ErrorMessaging__ui_column--3uMUS {
padding-left: 0;
}
But now I add a :global modifier onto .ui_column:
:global(.ocssContainer) {
:global(.ui_column) {
padding-left: 0;
}
}
And this is what it compiles to:
.ErrorMessaging__alertContainer--1I-Cz .ocssContainer .ui_column {
padding-left: 0;
}
Now .ui_column can apply to any child element with that style, including in a child React component, and not just .ui_column elements that are part of the ErrorMessaging React component.
It looks like they are using CSS Modules. If you follow the docs they say:
:global switches to global scope for the current selector resp.
identifier. :global(.xxx) resp. #keyframes :global(xxx) declares the
stuff in parenthesis in the global scope.
The :global selector keyword is used in css modules to specify that a class should not be scoped to the component in which it is defined. This selector allows the class to be used globally in the application, rather than just within a specific component. For example, let say you have a .is-global-class class defined in a CSS Module file, you can use :global(.is-global-class) to apply that class to an element and make it available globally.

Resources