ReactJS: Extend, Override CSS class - css

I want to
import a style class from a CSS file
dynamically extend or override the style
Apply the new style to react component.
Pseudocode of what I want to achieve
import 'common.css'
function MyComponent() {
if (somethingHappened) {
style = extendOverrideStyle(styleClassFromCSS)
} else {
style = styleClassFromCSS
}
return (
<SomeComponent className=style />
)
}
How can I do this?
Update:
Check my answer in the replies for how I finally did this.

Just create a new class in your CSS file to override the old CSS.
Then do it as
function MyComponent() {
return (
<div className={somethingHappened ? 'firstclass overwriteclass' :
'firstclass'}>
<SomeComponent />
</div>
)
}

You can't set style in Component Directly.
First you need to pass the style as prop to your Component and set style inside that component
<SomeComponent prop_class={your_style}/>
Inside SomeComponent
<div className={this.props.your_style}>
</div>

Answer (implementation somewhat similar to #Rohan's answer):
The main css class is the base style rules and .main.somethingHappened extends/overrides it. The main css class is applied to myComponent initially. When somethingHappened is true, apply both css classes main somethingHappened to myComponent.
mystyle.css
.main {
...
margin: 10px;
}
.main.somethingHappened {
margin: 5px
padding: 5px;
}
myComponent.js
(uses classnames library. check #Rohan's approach to avoid classnames library.)
import 'common.css'
import classnames from 'classnames'
function MyComponent() {
let didItHappen = ...
return (
<SomeComponent
className={classnames('main', {'somethingHappened': didItHappen})}
/>
)
}

Related

why same style applies to both components having different scss files with different styles in React?

I have two Components Login and Register with different separate styles.
// Login.jsx
import "../../Login.scss";
function Login() {
return (
<>
<div>Login</div>
</>
);
}
export default Login;
// Register.jsx
import React from "react";
import "../../Register.scss";
function Register() {
return (
<>
<div>Register </div>
</>
);
}
export default Register;
I have set different background color of both files, that is
// Login.scss
div{
background-color: red;
}
// Register.scss
div{
background-color: aqua;
}
I have rendered both components in App.js
but both the components have only one style applied i-e Register.scss even I have not imported it in Login.jsx but still in Login.jsx getting the style of Register.scss instead of Login.scss
what could be the possibl reason?
Can I apply same className styles by differentiating with different import paths?
This is due to the way that Cascading Style sheets work. The .div will adhere to the LAST style rule, as the file is read.
The post below contains the answer.
How to use the same name classes but in separate styles

How to extend styles in react component?

I have a task when I need to extend the styles of a certain element. I take the basic styles through the module, and the additional ones will need to be done inside the function that will be in the component.
How can I extend the styles inside the component if I have already added styles from the module there?
import style from './styles.module.css';
const optionalStyles = {
margin: "30px"
}
<p className={`${style.subtitle} ${optionalStyles}`}>42</p>
<p style={optionalStyles} className={`${style.subtitle}`}>42</p>
You can:
Create another class inside your styles.module (or any other module) and add it conditionally:
import style from './styles.module.css';
<p className={`${style.subtitle} ${someCondition ? style.otherStyles : ''}`}>42</p>
Use inline styles:
import style from './styles.module.css';
const optionalStyles = {
margin: "30px"
}
<p className={style.subtitle} style={someCondition ? optionalStyles : {}}>42</p>

How can I style :host element dynamically based on parameter from #Input?

Usually, I can style the very root of my component by using the :host pseudo style like this.
:host{ border: 1px solid gold; }
But how shold I handle if said style is supposed to be set dynamically, based on the parameters passed to #Input?
The only way I can think of at the moment is to add an auxilliary DIV and style it like so.
<div [ngClass]="styleMeDynamically"> ... </div>
Is there a way to apply a style dynamically directly on the host without the injected DIV?
I've found this suggestion but it requires explicitly stating the classes and connecting them to separate inputs. I'd like to get a config object as passed in parameter and bind the styling using [ngClass] to retail full flexibility.
Probably #HostBinding decorator can help you. It allows to bind any host attribute including class and style. For example:
#Component({ ... })
export class MyComponent {
// you can conditionally add a class to the host element
#Input()
#HostBinding('class.large')
large = false;
// it's possible to bind a style as well
#Input()
#HostBinding('style.border.px')
borderWidth = 1;
#Input()
green = false;
// and you can use a getter
#HostBinding('style.border-color')
get borderColorStyle() {
return this.green ? 'green' : 'black';
}
}
Since angular 9 it should be possible even to bind a CSS variable, see Improved CSS class and style binding section of the 9 version release article.
<div [style.--main-border-color]=" '#CCC' ">
<p style="border: 1px solid var(--main-border-color)">hi</p>
</div>
What you can do is,
Create a custom directive that will accept a style object. and inside that directive, you can get the reference of host element and modify its style.
Here is a Demo
And here is a quick explanation.
Create a directive as which will accept a style object.
import {Directive,TemplateRef,ElementRef,OnChanges,SimpleChanges,OnInit,Renderer2,DoCheck,Input} from "#angular/core";
#Directive({
selector: "[appSetStyle]"
})
export class SetStyleDirective implements OnInit, OnChanges {
#Input() appSetStyle: { [key: string]: any } = {};
constructor(private elementRef: ElementRef<HTMLElement>) {}
ngOnInit(): void {}
ngOnChanges(changes: SimpleChanges): void {
this.applyStyles();
}
applyStyles(): void {
if (this.appSetStyle) {
for (const key in this.appSetStyle) {
this.elementRef.nativeElement.style[key] = this.appSetStyle[key];
}
}
}
}
Use that style object with any html element or any other component in your project.
<app-header [appSetStyle]="dynamicStyles"></app-header>
If you don't want to make a directive then you can inject the ElementRef inside the component itself which you want to style.
ElementRef is the what you need to use to get the reference of host.
I hope this will help.

Set the ClassName with state value in modular css in react

I am using modular css in react. I have to addClass to a <h2> how do I do that the problem is I am using modular css I know how to do it in normal css.Please Help.
Here is my component
import React, { Component } from 'react';
import style from '../css/MessageHeader.css';
class MessageHeader extends Component {
constructor(props) {
super(props);
this.state = {
name : "name"
}
}
render(){
return(
<div className={style.container}>
<div className={style.iconWrapper}>
<i className ="fas fa-angle-left"></i>
</div>
<div className={style.profileWrapper}>
<h2 className={this.state.name}>john appleseed </h2> //this is how I would in normal css
</div>
</div>
);
}
}
export default MessageHeader;
This would help you add the className this way. Variable is any variable in state with classname
<h2 className={`${this.state.variable}`}></h2>
While you can use a global class, I'm assuming you also want the h2 classes to be scoped to that component. Just like your other classes, you need to reference the style import - but use a dynamic key based on the state, like so:
<h2 className={style[this.state.name]}>john appleseed </h2>
Then your css module MessageHeader.css should contain a class for all names that you want to custom styling for.
Example:
.container {
// some styles here
}
.johnAppleseed {
color: yellow;
}
// You can also specify a name as a child of the container just like normal css,
// although it's not really necessary
.container .bobBobbert {
color: red;
}
Keep in mind that if your name in the state has spaces, that isn't going to work for a css class name, so you'll have to do some transformation (e.g. this.state.name.replace(...) to remove spaces and/or punctuation.

CSS Modules, React and Overriding CSS Classes

I am using a React component library (React Toolbox), which is outputting this class in their Tab component using CSS Modules and Webpack: label___1nGy active___1Jur tab___Le7N The tab is a className prop I am passing down. The label and active classes are coming from the library. I want to apply a different set of styles on active, something like .tab.active where tab is referring to the styles I have created and active matches the generated selector the library has created but cannot figure out how to do this with css-modules. I need to override this dynamically selector: .label___1nGy.active___1Jur.
[]]2
[]3
Old post but still relevant, so adding an answer to help those with similar issue
While not inherently possible in CSS modules alone, the author of the react-toolbox library has actually solved this particular problem very nicely
Read their github docs which are more in depth on the subject at https://github.com/react-toolbox/react-toolbox#customizing-components
A list of the themeable classes for a particular component is given on the component demo page on their site too
In your case as well as passing a className for tab, you would also create a theme with classes that overrides that desired parts of the default theme and pass that as the theme prop. For example something alog the lines of...
MyComponentWithTabs.css
.tab {
color: white;
}
MyTabTheme.css
.active {
color: hotpink;
}
MyComponentWithTabs.js
import styles from './MyComponentWithTabs.css'
import tabTheme from './MyTabTheme.css'
// blah blah...
return <Tab key={index} className={styles.tab} theme={tabTheme} />
Under the surface this uses a decorator they have abstracted into separate library react-css-themr, I recommend giving that a read too as it explains how the defaults are composed with your overrides in much greater depth, including the different merging strategies they use
I had a similar case, and I solved it like so:
import classNames from 'classnames';
...
const activeClassName = {};
activeClassName[`${styles.active}`] = this.props.isActive;
const elementClassNames = classNames(styles.element, activeClassName);
return <div className={elementClassNames} />
I'm using the classnames package to dynamically add the active class based off of the isActive prop. Instead of an isActive prop you can provide any boolean value.
A more terse way of doing this may be:
const elementClassNames = classNames(styles.element, {[styles.active]: this.props.isActive});
CSS modules won't allow you to safely override the active className (largely by design). Really it should be exposed via an API, e.g. 'activeClassName'.
If the maintainers disagree or you need this quick then you can quite easily add your own active className because your implementing component is managing the index state:
import {Tab, Tabs} from 'react-toolbox';
import styles from './MyTabs.css';
class MyTabs extends React.Component {
state = {
index: 1
};
handleTabChange(index) {
this.setState({ index });
}
render() {
const { index } = this.state;
return (
<Tabs index={index} onChange={this.handleTabChange}>
<Tab label="Tab0" className={index === 0 ? styles.active : null}>
Tab 0 content
</Tab>
<Tab label="Tab1" className={index === 1 ? styles.active : null}>
Tab 1 content
</Tab>
</Tabs>
);
}
}
Disclaimer: Code is untested.
Group style loader
You can use the group-style-lader to override the style of the components. This loader gives you an easy and intuitive way of override the style of the components.
Configure the loader
Install the loader
npm install --save-dev group-style-loader
Configure the loader in your webpack settings
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'group-style-loader',
'style-loader',
{
loader: "css-loader",
options: {
modules: true
}
}
]
}
]
}
};
You only need to put it, before the style-loader or the mini-css-extract-plugin loader.
Override the style of the components
The next example show as you can to override the style of the Card component from the App component.
You can define the style of your component as you are used to.
card.css
.container {
width: 300px;
height: 400px;
border-radius: 8px;
}
.title {
font-weight: bold;
font-size: 24px;
}
.summary {
margin-top: 24px;
font-size: 20px;
}
The unique difference is that in the Card component, you going to use the mergeStyle function to merge the custom style with the default style of the component.
card.jsx
import React from 'react';
import { mergeStyle } from './card.css';
export function Card({ customStyle }) {
const style = mergeStyle(customStyle);
return (
<div className={style.container}>
<div className={style.title}>Title</div>
<div className={style.summary}>
Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor.
</div>
</div>
)
}
Then, in the App component, to override the style of the Card component you need to define the custom style of the Card component using the separator _. All the classes using this separator going to be grouped in the card property of the style object.
app.jsx
.title {
font-size: 32px;
font-weight: bold;
margin: 44px;
}
.list {
display: flex;
}
.card_title {
color: blue;
}
.card_summary {
color: green;
}
Finally, you only need to pass the custom style of the Card component through the customStyle property of it.
app.jsx
import React from 'react';
import { Card } from './card';
import { style } from './app.css';
export function App() {
return (
<div>
<h1 className={style.title}>Group style</h1>
<div className={style.list}>
<Card/>
<Card customStyle={style.card}/>
</div>
</div>
);
}
In the previous example, you have two Cards components, the first uses its default style, and the second uses the customs tyle that we have defined.
You can see a full explanation of how to use the group-style-loader in its repository.
Using :global(.classname) you can override the external classnames.
Even 3rd party library css can be override.
:global(.active) {
color: hotpink;
}
trick in fileName.css
add className-active after declaring className
.className{
background: white;
}
.className-active{
background: black;
}
<div className={'className className-active'} />
<div className={'className-active className'} />
divs always will be black

Resources