I want to change the CSS property based on if a user has clicked on dark mode or light. I can get the a subscription going to capture the value every time the modes are switch but i want to be able to change certain property's in CSS when the different modes are clicked.
I'm using Angular 9
Any idea on how I can do this?
You can use BehaviourSubject RXJS to implement this feature. By default you can set to false and use light mode when ever User clicks the switch using next() method change the behaviour subject to true then dark etc. you have to subscribe to BehaviourSubject variable on init and handle the response.
You can have the reference at BehaviourSubject.
I personally implemented this dark mode feature in my project here is the link telivic.com the approach I have used in that site is as followed.Hope this works for you.
addDark(){
document.getElementById('nav').classList.add('dark');
document.getElementById('box').style.backgroundColor = "#35363A";
document.getElementsByTagName("BODY")[0].classList.add('dark');
document.getElementById('modal').style.backgroundColor ="bisque";
if(this.service.flag){
document.getElementById('opt').classList.add('dark');
}
document.getElementById('gen').style.color="white";
}
removeDark(){
document.getElementById('nav').classList.remove('dark');
document.getElementById('box').style.backgroundColor = "#fff";
document.getElementsByTagName("BODY")[0].classList.remove('dark');
document.getElementById('modal').style.backgroundColor ="white";
if(this.service.flag){
document.getElementById('opt').classList.remove('dark');
}
document.getElementById('gen').style.color="black";
}
/*Binded my switch to this function I have used service so that user dark/light mode preference can be processed in other pages also.*/
darkMode(){
this.dark = !this.dark;
this.userService.setMode();
if(this.dark){
this.addDark();
}else{
this.removeDark();
}
}
You can use styled-components. One example would be:
import styled from 'styled-components'
const ComponentName = styled.div`
color: ${props => props.mode === `dark` ? `white` : `black`};
`
And then in your render, do this:
<ComponentName mode={mode} />
You can add a variable in ts file,
modeType: string;
This will change as 'dark' or 'light' depending on user's selection.
In your html to change the css property use ngClass.
Or use
<div class="{{modeType == 'dark' ? 'dark-property': 'light-property'}}">
In your css file,
.dark-property{
add your "dark" css styles
}
.light-property{
add your "light" css styles
}
Related
I am developing a library of react components and asked an important question. How to correctly change styles (css) when changing the application theme.
Appeal to those who already have experience in this and who can advise their approach or solution.
Now I'll tell you how it works for me:
I have my own themeProvider wrapped in a Context with the ability to change the theme.
When the theme changes in the provider, the changeCssVariables method is called.
export const changeCssVariables = (theme) => {
const root = document.querySelector(':root');
// root.style.setProperty('--default-color', 'orange');
const cssVariables = [
'color',
'background',
'color-uibutton',
'background-uibutton',
'box-shadow-uibutton',
'color-disabled-uibutton',
'background-disabled-uibutton',
'background-uiradiobutton',
'color-uiinputext',
'color-notes-uiinputext',
'color-subsection',
'background-subsection',
'box-shadow-subsection',
'alt-subsection',
'on-subsection',
'off-subsection',
];
cssVariables.forEach(element => {
root.style.setProperty(
`--default-${element}`,
`var(--theme-${theme}-${element})`
);
})
}
What happens in general: it has a global CSS with variables default, light and dark themes. When changing the theme, a method is called that changes the default variable to the variable of the selected theme.
Example css:
--default-color: var(--theme-light-color);
/* Themes */
--theme-light-color: #000;
--theme-dark-color: #fff;
I don't like that you have to pull in all the css and change it this way. What is the solution?
Thanks for the help!
Found a solution in using styled-components package
Created my wrapper as ThemeProvider (Context)
I have the following css which is loaded into my project:
// Default theme (light mode)
:root {
/* Typography */
--col-body-text: #0b0c0c;
--col-body-text-light: #505a5f;
}
// Dark mode theme
:root.dark {
/* Typography */
--col-body-text: #c5c5c5;
--col-body-text-light: #f8f8f8;
}
In my actual app this works as expected, however, in storybook, it ignores the dark mode variables.
I have updated my preview.js file to add '.dark' to the `HTML element when dark mode is selected - which works as expected - indeed all of the other dark mode specific code in the components works fine. It's only those variables that are being ignored.
Is there an issue with using :root in storybook that I'm not aware of or something?
if it helps, here is the code that adds the class to the HTML element:
// get an instance to the communication channel for the manager and preview
const channel = addons.getChannel()
// switch body class for story along with interface theme
channel.on('DARK_MODE', isDark => {
if (isDark) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
})
If you place such stylesheet in the HTML page (e.g. in the <head>), the :root selector refers to <html> (https://developer.mozilla.org/en-US/docs/Web/CSS/:root). If you want to use the :root selector with a class, you need to set the class on the <html> element (rather than on <body> suggested in another answer), so document.documentElement.classList.add('dark') is correct.
There is a playground which uses the Storybook syntax and features where I created a working example for you: https://webcomponents.dev/edit/p8TI3583HotsFNWjBMd8/src/index.stories.js
Not sure if your Storybook is configured in another manner, maybe your stylesheet is not really added or gets overwritten somewhere later. Please also verify if you use the CSS Custom Properties (aka CSS vars) correctly, I hope the working demo helps there too.
try
CSS -> body.dark {
instead of :root.dark {
and
channel.on('DARK_MODE', isDark => document.body.classList.toggle('dark', isDark))
I am trying to create a Design System using ReactJS and TailwindCSS.
I created a default Button component with basic styling as follow:
import React from "react";
import classNames from "classnames";
const Button = React.forwardRef(
({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames(
className,
"w-24 py-3 bg-red-500 text-white font-bold rounded-full"
);
const commonProps = {
className: buttonClasses,
onClick,
ref
};
return React.createElement(
"button",
{ ...commonProps, type: "button" },
children
);
}
);
export default Button;
I then use the Button in my page like:
import Button from "../src/components/Button";
export default function IndexPage() {
return (
<div>
<Button onClick={() => console.log("TODO")}>Vanilla Button</Button>
<div className="h-2" />
<Button
className="w-6 py-2 bg-blue-500 rounded-sm"
onClick={() => console.log("TODO")}
>
Custom Button
</Button>
</div>
);
}
This is what is displayed:
Some attributes are overridden like the background-color but some aren't (the rest).
The reason is the classes provided by TailwindCSS are written in an order where bg-blue-500 is placed after bg-red-500, therefore overriding it. On the other hand, the other classes provided in the custom button are written before the classes on the base button, therefore not overriding the styles.
This behavior is happening with TailwindCSS but might occurs with any other styling approach as far as the class order can produce this scenario.
Do you have any workaround / solution to enable this kind of customisation?
Here is a full CodeSanbox if needed.
One approach is to extract classes from your component using Tailwind's #apply in your components layer.
/* main.css */
#layer components {
.base-button {
#apply w-24 py-3 bg-red-500 text-white font-bold rounded-full;
}
}
// Button.js
const Button = React.forwardRef(({ children, className = "", onClick }, ref) => {
const buttonClasses = classNames("base-button", className);
// ...
);
This will extract the styles into the new base-button class, meaning they can easily be overwritten by the utility classes you pass to the Button component.
Another approach to create reusable React components using Tailwind is as follows..
Read this gist
https://gist.github.com/RobinMalfait/490a0560a7cfde985d435ad93f8094c5
for an excellent example.
Avoid using className as a prop. Otherwise, it'd be difficult for you to know what state your component is in. If you want to add an extra class, you can easily extend.
You need a helper for combining classname strings conditionally. Robert, the writer of this gist, shared the helper function also with us:
export function classNames(...classes: (false | null | undefined | string)[]) {
return classes.filter(Boolean).join(" ");
}
To have Tailwind CSS override material theming (or something else for that matter) one could apply !important to all tailwind utilities with configuration to module.exports.
The important option lets you control whether or not Tailwind’s utilities should be marked with !important. This can be really useful when using Tailwind with existing CSS that has high specificity selectors.
To generate utilities as !important, set the important key in your configuration options to true:
tailwind.config.js
module.exports = {
important: true
}
https://tailwindcss.com/docs/configuration#important
To solve, I recommend doing what Bootstrap does. Use a default class for your default button like:
.button {
width: 2rem;
background-color: red;
border-radius: 0.25rem;
}
Then when customizing a button you should apply classes that either come after the button class in your CSS file, or come in a different CSS file that is called after your default CSS file, or use the !important declaration.
Old answer
Use your browser developer tools to observe how your browser is loading CSS styles on an element. For example, in Chrome, right-click on the custom button and select "Inspect". A DevTools window will open and the element will be highlighted in the DOM.
On the right, you should have a Styles pane. There, you'll see a list of all the CSS styles being applied to the element. Styles with strikethroughs are being overridden by styles called by other CSS classes or inline styles.
In your case, the custom button has both the "CommonProps" classes and the classes you're adding in IndexPage. For example, both class w-6 and class w-24.
Class w-24 is overriding class w-6 because of CSS precedence. Read more about CSS precedence here. Check out rule #3 in the accepted answer. I think that's what's happening to you.
To solve, you may want to remove some classes from commonProps. Or use the !important declaration on some classes. This is the part of your design system that you need to think through. Look at how other systems like Bootstrap have done it.
I'm building a site in Hugo. I'm using the hello friend ng theme. I want to add a svg image to the main site, but I want it to change depending on whether the selected theme is light or dark.
That theme toggle is handled by theme.js:
const theme = window.localStorage && window.localStorage.getItem("theme");
const themeToggle = document.querySelector(".theme-toggle");
const isDark = theme === "dark";
var metaThemeColor = document.querySelector("meta[name=theme-color]");
if (theme !== null) {
document.body.classList.toggle("dark-theme", isDark);
isDark
? metaThemeColor.setAttribute("content", "#252627")
: metaThemeColor.setAttribute("content", "#fafafa");
}
themeToggle.addEventListener("click", () => {
document.body.classList.toggle("dark-theme");
window.localStorage &&
window.localStorage.setItem(
"theme",
document.body.classList.contains("dark-theme") ? "dark" : "light"
);
document.body.classList.contains("dark-theme")
? metaThemeColor.setAttribute("content", "#252627")
: metaThemeColor.setAttribute("content", "#fafafa");
});
But i don't know how to access the variable it's using.
I didn't manage to do exactly that, but I found a workaround which satisfies my needs, so I'm posting it in case someone finds it valuable.
Rather than using <img> with links to different svg images, I decided to use <svg> and copy the content of my image there, since it's just xml. Then, I removed properties such as stroke and fill, wrapped that <svg> in a <div with a custom class that I then control by css.
I'm not sure if that's the best approach but it seems to work for me.
I seem to be having some issues in regards to styling the components without using a theme. I just want to change a couple of colors without needing to create a new theme per element.
In this case, I just want to change the color of the bar to a brownish color and right now I have an input class as follows:
import style from './style.scss'
const TextInput = (props) => {
<Input className={style.textInput} {...props} />
}
And in my style.scss file:
.textInput {
.bar {
background-color: #663300;
}
}
Any help would be appreciated.
ClassName doesn't work like that.
You can't pass a Css style to a className, that is wrong.
Either pass the class names you want to apply as a string (in your case I guess it would be className="textInput bar") or you can create a className with classNames library (in any case the final result will be a string).
Just make sure you're styles are included in the page that the component is going to render and react will be smart enough to render the correct css class for each component.
As you can check in here ClassName is a string