How to extend styles in react component? - css

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>

Related

How to make visible private classes into specific stylesheet?

Is it possible to access css classes from css modules in a specific css stylesheet? For example I have mediaQueries.css witch I want to connect at the end of my markup of components, but I can't see within mediaQueries.css private classes of aboute.module.css or index.module.css. So how can I configure webpack or what can I do?
Import them as an object and reference the classes as properties:
import styles from "./path/to/stylesheet.module.css";
export default function Component() {
return <div className={styles.className}>hello world</div>
}
Example CSS:
.className {
color: red;
}
For regular stylesheets just import the CSS file:
import "./path/to/stylesheet.css";

ReactJS: Extend, Override CSS class

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})}
/>
)
}

React JS How to make components unaffected by CSS?

import React, { Component } from "react";
import './navbar.css'
class NavBar extends Component {
render() {
return (
<div>
navbar stuff
</div>
);
}
}
export default NavBar;
If I were to import NavBar to another file and place it.
import React, { Component } from "react";
import NavBar from './NavBar'
import './randomfile.css'
class somefile extends Component {
render() {
return (
<div id="test">
<NavBar />
</div>
);
}
}
export default somefile;
How do I prevent the CSS to affect my navbar? I'm trying to work with components but I've fallen into a bunch of CSS on my components when I just want the CSS i have in my NavBar file
randomfile.css
#test div {
text-align: left;
}
^ Makes everything under div align to the left
it depends on how the other css files are written like if they use very general rules such as elements matches so there is no way to prevent 100%. However you can minimize the impact by using.
Follow BEM for your styles, http://getbem.com/, so your styles will be tighter and it is usually specific for your components.
Use css in js libraries like styled-components, https://www.styled-components.com/, this way your css rules will be very strong and it is often enough to rule other rules outside.
I my self used to use BEM before, recently I have adopted css in js and been using styled components for most of my projects recently and it works quite well.

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.

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);

Resources