Tailwind ignoring darkMode: "class", not paying attention to class="dark" on html tag - reactjs

Using tailwind and react, I am using a config file as follows:
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
darkMode: "class",
important: "#app",
theme: {
colors: {
...
},
fontFamily: {
...
},
extend: {},
},
plugins: [],
corePlugins: {
preflight: false,
},
};
and setting the class as follows
darkMode
? document.documentElement.classList.add("dark")
: document.documentElement.classList.remove("dark");
Inspecting the top element, it is indeed adding and removing a class="dark" to the top element. However, two elements like
text-grey-300 dark:text-grey-700
aren't changing when the class changes, at all. When the darkMode: Class is removed, it accurately follows OS preference however. Whats going on?
I have tried changing the class selector manually, tried placing the dark on other elements, moving the declaration around in my config file, none of it seems to help.

Related

Why does Tailwind not display the proper bg color when starting a development server?

I am currently using ReactJS(TypeScript) with TailwindCSS to create some forms, and I want my Submit button to use one of the yellow colors that come with Tailwind. However, when I have my react project running and I update the value to bg-yellow-300 , it will turn yellow, but when I first launch the react app, the button has its default color scheme, which I don't want. I've provided the code for the button below, and my config file:
<Button className="w-1/12 bg-yellow-300 hover:bg-yellow-400 text-black-100" type="submit">
Submit
</Button>
Config File:
/** #type {import('tailwindcss').Config} */
module.exports = {
mode: 'jit',
content: ["./src/**/*.{js,jsx,ts,tsx}", 'node_modules/flowbite-react/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {
colors: {
"gold":"#edcd37",
"babyblue":"#298ge5",
},
},
},
plugins: [
require('flowbite/plugin')
],
}
I've tried adding the JIT(Just in time) setting to see if for some reason that was why it wasn't giving the correct color on initial loading, but it didn't work either.

tailwind hover not working on my react app

I am working on magento 2 PWA using react and tailwind but all the classes in tailwind I can use but can't use hover.
Here is my tailwind.config.js:
// TODO #TW:
// Node path should be committed, but it makes preset dev impossible.
// Local path is the only way to develop "tailwind.preset.js".
const venia = require('#magento/pwa-theme-venia');
const config = {
mode: 'jit',
// Include your custom theme here.
presets: [venia],
// Configure how Tailwind statically analyzes your code here.
// Note that the Tailwind's `jit` mode doesn't actually use PurgeCSS.
purge: {
// Include paths to every file that may refer to Tailwind classnames.
// Classnames not found in these files will be excluded at build time.
content: [
'./src/**/*.{html,js}',
'./node_modules/#magento/venia-ui/lib/**/*.module.css',
'../venia-ui/lib/**/*.module.css',
'./src/**/*.module.css',
'./template.html'
],
theme: {
extend: {},
screens: {
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
'2xl': '1536px'
}
},
// Extract Tailwind classnames from source files.
// Our default matcher only matches targets of CSS Modules' `composes`,
// not classnames included directly in HTML or JS!
extractors: [
{
extensions: ['css', 'scss'],
extractor: content => content.match(matcher) || []
}
]
},
// Set the character Tailwind uses when prefixing classnames with variants.
// CSS Modules doesn't like Tailwind's default `:`, so we use `_`.
separator: '_'
};
module.exports = config;
/**
* Matches declarations that contain tailwind classnames.
* Only classnames matched by this expression will be included in the build.
*
* #example
* .foo {
* composes: mx-auto from global;
* }
*/
const matcher = /(?<=composes:.*)(\b\S+\b)(?=.*from global;)/g;
here is my postcss.config.js:
module.exports = {
plugins: [
require('autoprefixer'),
require('tailwindcss')('./tailwind.config.js')
]
};
How can I fix this issues???? Thank you so much!

Tailwind CSS, certain custom colors are not working

I'm trying to use Tailwind custom colors in my project by writing some themes in tailwind.config.js extend.
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
theme: {
extend: {
colors: {
s2condPurple: '#a32eff', // works ⭕️
s2condPink: '#ff0099', // works ⭕️
s2condOrange: '#ff5f55', // works ⭕️
s2condYellow: '#ffe600', // doesn't work ❌
s2condLime: '#cdff64', // works ⭕️
s2condMint: '#2af1b5', // works at 'text-s2condMint' but not at 'border-s2condMint'
secondTest: '#ffe600', // works ⭕️ <-- I tested it for s2condYellow but it works perfectly!
s2condTest2: '#2af1b5', // doesn't work ❌
...
},
},
},
plugins: [],
}
I'm using these colors in my code like this:
const colorList: colorListType = {
life: 'white',
identity: 's2condPurple',
arts: 's2condPink',
industry: 's2condOrange',
knowledge: 'secondTest',
sports: 's2condLime',
languages: 'secondTest',
}
const { [data.name.en.toLowerCase()]: color } = colorList
...
<button
className={`border focus:outline-none hover:border-${color} active:border-${color} ${
clicked ? `border-${color}` : 'border-textBlack'
} `}
>
<p className="text-white">{value.kr}</p>
</button>
Can I get a clue about this issue??
Newer versions of Tailwind only seem to add classes that have been used in your code. When using dynamic classes (like the ones in your example) you will have to declare them within the safelist property.
Here's an example of one way your could do this:
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
theme: {
extend: {
colors: {
s2condPurple: '#a32eff', // works ⭕️
s2condPink: '#ff0099', // works ⭕️
s2condOrange: '#ff5f55', // works ⭕️
s2condYellow: '#ffe600', // should work⭕️
s2condLime: '#cdff64', // works ⭕️
s2condMint: '#2af1b5', // works at 'text-s2condMint' but not at 'border-s2condMint'
secondTest: '#ffe600', // works ⭕️ <-- I tested it for s2condYellow but it works perfectly!
s2condTest2: '#2af1b5', // should work ⭕️
},
},
},
plugins: [],
safelist: [{
pattern: /(bg|text|border)-s2cond(Purple|Pink|Orange|Yellow|Lime|Mint|Test|Test2)/
}
]
}
You can read more about this in the documentation https://tailwindcss.com/docs/content-configuration#safelisting-classes.
Update: 8th June 2022
If you work with a lot of dynamic margins or dimensions, you might want to add the following to your safelist property.
{
pattern: /(mt|mb|mr|ml|my|mx|px|py|pt|pb|pl|pr)-[0-9]+/
},
{
pattern: /flex-.*/
},
{
pattern: /(bottom|right|top|left)-[0-9]+/
},
{
pattern: /(w|h)-[0-9]+/
}
Hope this saves someone else's time.
https://tailwindcss.com/docs/content-configuration#dynamic-class-names
Here's the answer.
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>. // ❌
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>. // ⭕️
I did it in a wrong way :(

I'm having this weird webpack.cache.PackageCacheStrategy

Below is the error on my console
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Using webpack 5. Reason: no custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
warn - You have enabled the JIT engine which is currently in preview.
warn - Preview features are not covered by semver, may introduce breaking changes, and can change at any time.
<w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|C:\Users\J.Andrew\Documents\WebDev\nextjs-boilerplate\node_modules\next\dist\compiled\css-loader\cjs.js??ruleSet[1].rules[2].oneOf[7].use[1]!C:\Users\J.Andrew\Documents\WebDev\nextjs-boilerplate\node_modules\next\dist\compiled\postcss-loader\cjs.js??ruleSet[1].rules[2].oneOf[7].use[2]!C:\Users\J.Andrew\Documents\WebDev\nextjs-boilerplate\node_modules\next\dist\compiled\resolve-url-loader\index.js??ruleSet[1].rules[2].oneOf[7].use[3]!C:\Users\J.Andrew\Documents\WebDev\nextjs-boilerplate\node_modules\next\dist\compiled\sass-loader\cjs.js??ruleSet[1].rules[2].oneOf[7].use[4]!C:\Users\J.Andrew\Documents\WebDev\nextjs-boilerplate\styles\globals.scss': No serializer registered for CssSyntaxError
<w> while serializing webpack/lib/cache/PackFileCacheStrategy.PackContentItems -> webpack/lib/NormalModule -> webpack/lib/ModuleBuildError -> CssSyntaxError
error - ./styles/globals.scss:1:1
Syntax error: Unknown word
wait - compiling...
error - ./styles/globals.scss:1:1
Syntax error: Unknown word
Here is global.scss mentioned in the error. When I try to removed the tailwind imports, it compiles without a problem. But I needed those in order for tailwind to work.
#import '~tailwindcss/base';
#import '~tailwindcss/components';
#import '~tailwindcss/utilities';
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
My tailwind.config.js
module.exports = {
mode: 'jit',
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
important: true,
theme: {
container: {
center: true,
padding: '1.5rem',
},
extend: {
colors: {
// 'nav-bg': '#383E4C',
},
},
},
variants: {
extend: {},
},
plugins: [require('#tailwindcss/forms')],
}
And my postcss.config.js which is default
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Please help...
Today I had the same problem. My code was working just fine, until I created a React component that had a function that uses querySelector, something like this:
const handleSomething = () => {
const x = 150;
let activeSlide = document.querySelector('.slide');
activeSlide.classList.add(`-translate-x-[${x}]`);
}
It seemed that the -translate-x-[${x}] statement was causing the bug. However, after removing this line, the problem didn't go away. I tried to delete the "node_modules" and ".next" folders and reinstall the dependencies, but nothing seemed to work.
I don't know what caused it, but the only way I could get the application to run again was to go back to the previous commit (with a git reset --hard HEAD - WARNING: be careful with this command because you loose all uncommitted changes, but that was my intention) and delete that component (the file itself). Even a simple copy and paste of the contents of this file, with most of the "weird" lines commented out (this function, basically), would make the error come back. Literally nothing else seemed to work for me.
It probably doesn't answer your question, but I hope it can help someone who is facing the same problem, until no better solution comes up.
As Renato mentioned in his answer, it seems dynamically constructing tailwind class names returns this error.
This is explained in the tailwind docs here:
Dynamic class names
As outlined in Class detection in-depth, Tailwind doesn’t actually run your source code and won’t detect dynamically constructed class names.
❌ Don't construct class names dynamically
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
✔️ Always use complete class names
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
Also from this documentation about how tailwind detects CSS class names:
The most important implication of how Tailwind extracts class names is that it will only find classes that exist as complete unbroken strings in your source files.
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS
Therefore to dynamically set a CSS property of an element, using the inline style provided by React.js would be the best way to do it. For example:
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
I had a similar issue that happened when I tried to add a preview of the filed I just choosed.
For that I used the URL object like that :
image.src = URL.createObjectURL(picture)
I just remove this part of my component the error was gone.

Module scss ampersand class selector not working

I have a simple scss file with
.navItem {
cursor: pointer;
&.active {
color: $primaryPurple;
}
&:hover {
color: $primaryPurple;
}
span {
margin-left: 10px;
}
}
For some reason, the :hover works but .active doesn't work. As you can see in the image below, li clearly has the active class but I don't see the font color css changed.
TL;DR: Pass the name as a JavaScript Object, not like a simple string.
Actually, this issue comes from the css-modules configuration. Obviously, based on the AdminSideBar_navItem__1aFBc in the embed picture. your css-modules configuration in the Webpack config is:
// webpack config
module.exports = {
~~~
module: {
~~~
rules: [
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
localIdentName: '[name]_[local]_[hash:base64:5]', // <=== Attention to this line
sourceMap: true,
}
},
~~~
],
}),
],
},
~~~
};
So, when you are using css-modules it means you will have so professional advantages like a more compressed css bundle file or full hashed unreadably uglified bundle. for these benefits, you should use CSS class names like a JavaScript object, pay attention to the following ReactJS code alongside using css-modules:
import React from 'react';
import cn from 'classnames'; // <=== install it to have easy coding
import styles from '[pathToScssFiles]/styles.scss';
const MyComponent = ({ isActive }) => (
<li className={cn(styles.navItem, isActive && styles.active)} />
);
I hope, you understand my point, you passed the styles.active as a simple string: "active". so css-modules cannot get your class name as an object and pass it exactly like what it got, as a simple string, hence, "active" **BUT** in the CSS bundle file the css-modulesuse the'[name][local][hash:base64:5]'` pattern to deform its name.
Your :hover should work and it works because anyone cannot change it, it's a pseudo-class.
For sure, write a weird property for .active:
.navItem {
cursor: pointer;
&.active {
fill: yellow;
}
Now seek for the fill: yellow in the CSS bundle that Webpack makes for you. you see it is:
.AdminSideBar_navItem__1aFBc .AdminSideBar_active__9be2a {
fill: yellow;
}
Note: the ~~~ means etc.
Providing you jsx code would help, but I will take a guess that you use active as a string literal, so your code looks like
import styles from './componentName.module.css';
// and then in the component
<li className={`nav-item ${styles.AdminSideBar_navItem} ${whateverCondition ? 'active' : ''}`}>
...children...
</li>
The problem here is that active class also has a suffix just like AdminSideBar_navItem. And in order to make it work you need to access it the same way you access AdminSideBar_navItem. So the code should be
<li className={`nav-item ${styles.AdminSideBar_navItem} ${whateverCondition ? styles.active : ''}`}>
...children...
</li>
and in html you will see
<li class="nav-item AdminSideBar_navItem_abcd active_bcde">
I dropped a simple example in this codesandbox, you can play around with it and see how it works.

Resources