how to apply different styles to Modal.Header for React-Bootstrap Modal component? - css

I'm new to React.
I'm trying to create 2 different styles of Modals with the React-Bootstrap Modal component: one with an orange header, and another white header (aka no header).
2 types of headers img
The style of modal used depends on where it's used. For example, I want the white header to appear for sign in and sign out, and only those 2 modals. Right now, the .modal-header CSS seems like the default style applied to any declaration of Modal.Header. My modal-header class has styling for the orange header:
.modal-header {
color: #fff;
background-image: linear-gradient(255deg, #f9b25e, #f17b30);
}
I don't want this style applied to the sign up and sign in modals. I tried creating this new CSS ID modal-no-header and adding it to the Modal.Header declaration in the signup and signout js files:
in my CSS:
#modal-no-header{
background-color:#fff !important;
}
in SignupModal.js:
render() {
return (
<Modal show={this.props.showModal} onHide={this.props.closeModal} >
<Modal.Header id="modal-no-header" closeButton>
</Modal.Header>
<Modal.Body> blah... <Modal.Body>
</Modal>
)
}
However, the #modal-no-header styling isn't overriding the default .modal-header class:
not working, inspect element screenshot included
Question: Is this the right way to specify multiple styles for Modal components in React-Bootstrap? If not, is there a better method and how do you go about it? I checked out the documentation but wasn't able to spot anything helpful. Thanks in advance.

Related

Ionic 6 styling of ion-datetime

I have stumbled upon some difficulties styling ion-datetime component using ionic 6, and none of the posts seem to contain a solution for this. I would like to apply some custom styles to picker items that appear in the shadow-root part.
Applying CSS to classes like .picker-item and .picker-item-active doesn't do anything because they are in the shadow-root. And there don't seem to be any styling properties and variables for ion-picker that I could use.
I am using the standard ion-datetime component like this:
<ion-datetime presentation="time"></ion-datetime>
and in the simulator while inspecting the HTML it appears as:
Styling that I would like to change:
Color and font properties for picker items
Color, background and font properties for active picker item
Since they are all open shadowRoots, you can get in and inject a <style> sheet:
document.querySelector("ion-datetime")
.shadowRoot.querySelector("ion-picker-internal")
.shadowRoot.querySelector("ion-picker-column-internal")
.shadowRoot.prepend( Object.assign( document.createElement("style") , {
innerText : `
.picker-item {
background:hotpink
}
`
}));
After some more playing around, I have been able to find a solution and customize it to my project needs. Thanks to Danny '365CSI' Engelman for inspiration.
The use of ion-datetime and its customization in my project is complex due to using multiple ion-datetime elements appearing and disappearing dynamically. Therefore, applying custom styling of it required some additional logic not posted here. Please reach out if you need some help regarding this.
Here is the base logic that allowed me to apply some styles to ion-datetime:
document.querySelectorAll("ion-datetime").forEach(dt => {
var el = dt.shadowRoot.querySelector("ion-picker-internal");
el.shadowRoot.prepend(Object.assign(document.createElement("style"), {
innerText: `
.picker-highlight {
background: red !important;
}
`
}));
el.querySelectorAll("ion-picker-column-internal").forEach(col => {
col.shadowRoot.prepend(Object.assign(document.createElement("style"), {
innerText: `
.picker-item {
color: green !important;
}
.picker-item-active {
color: blue !important;
}
`
}));
});
});

Prefix css selectors for make styles from API safe

Let's assume that the user can add styles for every component in admin panel and I get it as string in my Node server:
const stylesFromAPI = ".p { color: red } .bg { background: lime }";
How to prefix this styles before append to my document to avoid conflicts?
I need something like CSS modules but working with strings (not as module loader):
const stylesFromAPI = css(".p { color: red } .bg { background: lime }"); // returns hashedClassname685946898456
<SomeCompontent className={stylesFromAPI} />
produces:
<style>
.hashedClassname685946898456 .p { color: red }
.hashedClassname685946898456 .bg { background: lime }
</style>
<div class="hashedClassname685946898456"></div>
Shadow DOM seems like a reasonable option here. You can create your style tags with inside the shadow DOM without having to deal with any selector prefixes. For example, using the react-shadow package:
import root from 'react-shadow';
Then in JSX, something like:
<root.div>
<style type="text/css">
{/* CSS string here */}
</style>
<div>
{/* Stuff here */}
</div>
</root.div>
Check out a working example of this here: https://github.com/joshdavenport/stack-overflow-61566764-react-css-shadow-dom
The main downside here is your styles from outside the shadow DOM will not apply. Those using the shadow DOM for components see this as a good thing, those simply trying to scope CSS do not. Not sure what it is you're scoping, so I can't really tell if that would be an issue for you.
If it is, you could re-import your styles within the shadow DOM, though I can't really point out how to do that without knowing what bundler is in use and how it is in use.
Alternatively you could pull apart your imported CSS using the css package, iterate over the selectors prefixing all with a randomly generated class, and then re-stringify.

I want to apply a background image to the body of only one component

I am very new to React, so apologies for the mistakes in advance.
In my React app, say I have 2 components and as the CSS styles are global, it picks up CSS styles from all the files.
However, I wish to add a full background image to one of the components which I was able to achieve by using this code in my CSS file:
body {
background-image: url("../image.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
The problem is that the same image is also being applied to another component. I read a few answers and found that I can use ComponentDidMount hook and add the image to the body tag there. I tried that, but it doesn't show anything.
componentDidMount() {
document.body.style.backgroundImage = "url('../image.jpg')";
document.body.style.backgroundPosition = "center";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
}
EDIT
I realized I had the wrong wording for the question. What I mean to say is that I have two pages in React. For one of the pages, I want a full background image. However, because CSS styles are global, the background image is getting applied to all the pages.
You can use inline styling or specific styling by assigning a specific class or ID to the top element of one component.
INLINE STYLING Example:
// If Background variable has url to the background image.
const style = {
backgroundImage: `url(${Background})`
}
// in component use that inline style
return (
<div style={style}></div>
);
IF YOU WANT TO WORK with body only...
then add a class to body on component A mount and remove the class on component B mount. And attach the background property to the class.
A component usually return some jsx and in most cases a div. In other to apply a css to a single component I mean the jsx the component is rendering. you should define a css class, that apply a background image to the div the component is rendering and make the height of the div the window height. you can do this via inline css all
const MainDiv =()=>(
<div classname="testClass">
This will show background image in the covering the entire body
//Other content of your page can be added here like the rest of your page contents
<header>
This is my blog post
</header>
<nav>
this is my navbar
</nav>
</div>
);
ReactDOM.render(<MainDiv />, document.getElementById("root"));
.testClass{
backgroundImage :"url('../image.jpg')";
backgroundPosition :"center";
backgroundRepeat : "no-repeat";
background-size : "cover";
width: 100%;
height: 100vh
}

How to disable Vuetify button without changing colors

I'm using Vuetify's v-btn button component with a variety of colors set via the color prop. Once a user clicks the button, I set disabled to true so they can't click it again, but the button loses its color and gets greyed out.
Is there any way to disable the button without changing its color to grey?
Instead of disabled prop you could use your custom class with pointer-events: none, e.g.
.disable-events {
pointer-events: none
}
<v-btn :class="{'disable-events': customCondition}">
Then add additional styling to that class if needed.
I do it by removing v-btn--disabled and playing with vuetify's css classes.
Still grey but with colored text solution
The button will still be grey, but text will be colored, like that you have a visual effect showing that the button is disabled but still have a colored part.
I, personally, also had some custom opacity to disabled buttons.
HTML
<v-btn id="btnA" :disabled="true" color="success">Success</v-btn>
CSS
button.v-btn[disabled] {
opacity: 0.6;
}
JS
created(){
// Trick to remove class after initialising form
this.$nextTick(() => {
document.getElementById('btnA').classList.remove('v-btn--disabled')
})
}
CodePen
Same display solution
If you really want, the same display you will have to remove [color]--text and add [color] class (and sometimes add white--text class for readability).
JS
created(){
// Trick to remove class after initialising form
this.$nextTick(() => {
document.getElementById('btnA').classList.remove('v-btn--disabled')
document.getElementById('btnA').classList.remove('success--text')
document.getElementById('btnA').classList.add('success')
})
}
CodePen
As Vuetify allready use important! in .v-btn--disabled it's not possible to just override this class. But with the use of a higher level selector like id (example: #custom-disabled which selects id="custom-disabled") you can. This doesen't keep the original colors but you are at least able to override the class to your liking.
<v-btn :disabled="true" id="custom-disabled">
Button
</v-btn>
<style>
#custom-disabled.v-btn--disabled {
background-color: red !important;
}
</style>
For light and dark theme:
<style>
#custom-disabled.v-btn--disabled.theme--light {
background-color: red !important;
}
#custom-disabled.v-btn--disabled.theme--dark {
background-color: brown !important;
}
</style>
Okay so you can do it by disabling the pointer events as mentioned in other comments but if someone is using a keyboard they can still tab to the control and if you are writing automated tests the button can still be clicked.
You can manually override the style and change the disabled button colour in the css however this will potentially be a problem if you are manually setting the color through the color="" property on v-btn based off a theme (because your application supports branding for different clients for example) because Vuetify doesn't just override the color, it stops adding the color altogether.
So my solution was to simply set the button color via a style attribute and set the important flag (to override the disabled important flag) note that you will need to change the text color as well.
<v-btn
:style="{
color: `${getTxtColor()} !important`,
backgroundColor: `${getBtnColor()} !important`
}"
:disabled="status"
#click="doSomething"
>
Click Here
</v-btn>
This approach should play nice with testing, themeing, and will not allow users to tab to the button accidentally.

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