Vue 3 with Tailwind using v-bind:class shows classes in html element but not render while style works correctly - data-binding

I am new to Vue and I'm trying to bind multiple classes in a v-for loop from a const array of object imported from a file.js.
But the trick I'm trying is to import const and than return classes from method that evaluates one property of object looped.
I've tried all ways, methods, computed, setup, onMounted, beforeMount, but even if i can see my classes in html they aren't rendered in styles section of DevTools.
The only way that works is to v-bind:style instead of class. Or just put exact classes in my const array object as a property but I prefer to avoid this.
It seems to save something in cache, but i have tried to delete and to lunch application in hidden mode but it won't works
Is there someone who can help me to understand and maybe to resolve?
Thanks in advance
this is my actual code:
<template>
<div id="cv" class="tp3-flex md:tp3-grid md:tp3-grid-cols-[repeat(27,_minmax(0,_1fr))] md:tp3-grid-rows-[repeat(6,_minmax(0, 5rem))] tp3-justify-center tp3-content-center tp3-justify-items-center tp3-mx-auto tp3-p-2 tp3-bg-cyan-500 tp3-text-blue-50">
<div v-for="(softSkill, index) in softSkills" :key="`softSkill-${index}`"
class="tp3-flex tp3-w-20 tp3-h-20 -tp3-rotate-45 tp3-rounded-full tp3-rounded-tr-none tp3-justify-center tp3-items-center tp3-bg-slate-400 tp3-opacity-70 tp3-mb-4 tp3-mt-4 tp3-shadow-md tp3-overflow-hidden"
v-bind:class="posCols(softSkill)">
<div class="tp3-rotate-45">
<span v-html="softSkill.text"></span>
</div>
</div>
</div>
</template>
<script>
import {softSkills} from "#/assets/skills/softSkills";
export default {
name: "ComponentSoftSkills",
data(){
return{
softSkills: null
}
},
beforeMount() {
this.softSkills = softSkills;
},
methods: {
posCols(softSkill){
console.log(softSkill);
return ' tp3-col-start-['+softSkill.col+'] tp3-col-end-['+(softSkill.col+1)+']';
}
}
}
</script>
<style lang="css" scoped>
</style>
and my file.js is:
export const softSkills = [
{text:`skill 1`, col:1, row:1},
{text:`skill 2`, col:5, row:1},
{text:`skill 3`, col:2, row:2},
{text:`skill 4`, col:15, row:1},
]

I have a suspicion that this might be due to your tailwind setup.
Because the classes are assigned dynamically and tailwind (depending on the configuration) is only making classes available that it can find during compilation. So the classes, even though you see them populated correctly, are not made available through tailwind. simply put, when tailwind scans the code, it doesn't recognize md:tp3-grid-cols-[repeat(27,_minmax(0,_1fr))] or tp3-col-start-[${softSkill.col}] as a valid class name and does not generate the class for it.
Assuming this is the issue and not knowing the exact version on configuration can't give an exact solution, but here are some tips for it.
Instead of using dynamic class names, define all the class names and assign dynamically
so instead of using tp3-col-start-[${softSkill.col}] tp3-col-end-[${(softSkill.col+1)}]
you could make sure all possible classes are clear and accessible by the tailwind parser:
let colClass = `tp3-col-start-[0] tp3-col-end-[1]`;
if(softSkill.col === 1) colClass = "tp3-col-start-[1] tp3-col-end-[2]";
if(softSkill.col === 2) colClass = "tp3-col-start-[2] tp3-col-end-[3]";
if(softSkill.col === 3) colClass = "tp3-col-start-[3] tp3-col-end-[4]";
if(softSkill.col === 4) colClass = "tp3-col-start-[4] tp3-col-end-[5]";
if(softSkill.col === 5) colClass = "tp3-col-start-[5] tp3-col-end-[6]";
// ...etc
this is obviously very verbose, but the classes are clearly defined in the code, so tailwind can find them when scanning your code.
Safelisting classes
using safelisting of classes is another option. Instead of having the code in your js, you would have it in the configuration
// tailwind.config.js
module.exports = {
// ...other stuff
safelist: [
'tp3-col-start-[0]',
'tp3-col-start-[1]',
'tp3-col-start-[2]',
'tp3-col-start-[3]',
'tp3-col-start-[4]',
'tp3-col-start-[5]',
// ...etc
'tp3-col-end-[1]',
'tp3-col-end-[2]',
'tp3-col-end-[3]',
'tp3-col-end-[4]',
'tp3-col-end-[5]',
// ...etc
],
}
there's also a way to use regex, which might look something like this:
// tailwind.config.js
module.exports = {
// ...other stuff
safelist: [
{
pattern: /tp3-col-start-[(0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15)]/,
variants: ['sm', 'lg'], // you can add variants too
},
{
pattern: /tp3-col-end-[(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16)]/,
},
],
}
you can read more about safelisting here safelisting-classes

Related

SvelteKit Unused CSS selector warning in VS Code

How can I remove VS Code Unused CSS selector warning? This warning is in all files where i use <style lang="scss">. I know that I don't use .btn class in some components, but I want this class as global css.
my svelte.config.js:
const config = {
onwarn: (warning, handler) => {
const { code, frame } = warning;
if (code === "css-unused-selector")
return;
handler(warning);
},
preprocess: [
preprocess({
defaults: {
style: 'scss'
},
postcss: true,
scss: {
prependData: `#import 'src/scss/global.scss';`
}
})
],
};
Please can someone help me?
If you use prependData that means you add the import to every component where you use styles. This is not what you want, therefore remove this setting. What you want is to import this file once so it's available globally. This can be done by just importing it inside the script tag, SvelteKit (or rather: Vite) can handle style imports.
Inside your root __layout.svelte file, add
<script>
import 'path/to/your/global.scss';
</script>

JIT tailwindcss using variable in bg-[] not rendering color

when passing my color as props like this <List text="something" color="#84AB86" /> and using in the code className={'bg-[${color}] '} it does not render properly.
when looking at chrome dev tools color are added correctly like this bg-[#84AB86]
while putting the color manually without taking it from props, it does work correctly
after more testing it seems not possible either to do it like this
const color = "#84CC79"
className={`bg-[${color}]`}
any idea why
To use dynamic classes with JIT tailwind you either need to use safelist config key or create stub file where you list all your dynamic classes that you will use.
Config example:
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
'bg-red-500',
'text-3xl',
'lg:text-4xl',
]
// ...
}
Or make safelist.txt in your src folder, then add classes there just like so:
bg-[#84AB86]
bg-[#fffeee]
// etc..
And don't forget to include this safelist.txt file to your config content so tailwind could watch it.
Explanation from tailwind docs
If you are not using JIT, then you can use safelist option for PurgeCSS:
// tailwind.config.js
module.exports = {
purge: {
// Configure as you need
content: ['./src/**/*.html'],
// These options are passed through directly to PurgeCSS
options: {
// List your classes here, or you can even use RegExp
safelist: ['bg-red-500', 'px-4', /^text-/],
blocklist: [/^debug-/],
keyframes: true,
fontFace: true,
},
},
// ...
}
From the Tailwindcss documentation
Dynamic values Note that you still need to write purgeable HTML when
using arbitrary values, and your classes need to exist as complete
strings for Tailwind to detect them correctly.
Don't use string concatenation to create class names --> <div className={mt-[${size === 'lg' ? '22px' : '17px' }]}></div>
Do dynamically select a complete class name --> <div className={ size === 'lg' ? 'mt-[22px]' : 'mt-[17px]' }></div>
Tailwind doesn’t include any sort of client-side runtime, so class
names need to be statically extractable at build-time, and can’t
depend on any sort of arbitrary dynamic values that change on the
client. Use inline styles for these situations, or combine Tailwind
with a CSS-in-JS library like Emotion if it makes sense for your
project.
As mentioned above tailwind engine In order to render a custom class dynamicaly:
Does not like:
className={`bg-[${custom-color}]-100`}
It expects:
const customBgColorLight = 'bg-custom-color-100';
className={`${customBgColorLight} .....`}
For this to work properly you have to include the name of the class in the safelist:[] in your tailwind.config.js.
For tailwind v.3
/** #type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{js,jsx,ts,tsx}'],
safelist: [
'bg-custom-color-500', // your-custom-css-class
'text-custom-color-500',
'border-custom-color-500',
..... // other classes
'hover:bg-custom-color-500', // *** also include it with the selector if needed ***
.... // other classes
],
theme: {
extend: {
colors: {
'custom-color': { // you have to use quotes if key is not in camelCase format
100: '#d6d6d6',
500: '#5E8EA2',
..... //other variants
},
...... // other colors
So you can use it:
// if you want store the values to an object
const yourClassObj = {
customBgColor: 'bg-custom-color-500',
customBrdColor: 'border-custom-color-500',
customTxtColor: 'text-custom-color-500',
};
const { customBgColor, customBrdColor, customTxtColor } = yourClassObj;
<YourComponent
className={`mb-2 font-semibold py-2 px-4 rounded-lg
${ conditionGoesHere ? `${customBgColor} text-white cursor-default`
: `${customTxtColor} border ${customBrdColor}
bg-transparent hover:border-transparent
hover:${customBgColor} hover:text-white`
}`}
/>
An easy solution is to use the built in style property.
For example in React:
Dont Use:
className={`bg-[${color}]`}
Use Instead:
style={{
backgroundColor: color,
}}

Change css variables dynamically in angular

In my angular project, I have some css variables defined in top level styles.scss file like this. I use these variable at many places to keep the whole theme consistent.
:root {
--theme-color-1: #f7f7f7;
--theme-color-2: #ec4d3b;
--theme-color-3: #ffc107;
--theme-color-4: #686250;
--font-weight: 300
}
How can I update values of these variables dynamically from app.component.ts ? And What is the clean way to do this in angular ?
You can update them using
document.documentElement.style.setProperty('--theme-color-1', '#fff');
If u want to update many values, then create a object
this.styles = [
{ name: 'primary-dark-5', value: "#111" },
{ name: 'primary-dark-7_5', value: "#fff" },
];
this.styles.forEach(data => {
document.documentElement.style.setProperty(`--${data.name}`, data.value);
});
The main thing here is document.documentElement.style.setProperty. This line allows you to access the root element (HTML tag) and assigns/overrides the style values.
Note that the names of the variables should match at both places(css and js files)
if you don't want to use document API, then you can use inline styles on HTML tag directly
const styleObject = {};
this.styles.forEach(data => {
styleObject[`--${data.name}`] = data.value;
});
Then In your template file using ngStyle (https://angular.io/api/common/NgStyle)
Set a collection of style values using an expression that returns
key-value pairs.
<some-element [ngStyle]="objExp">...</some-element>
<html [ngStyle]="styleObject" >...</html> //not sure about quotes syntax
Above methods do the same thing, "Update root element values" but in a different way.
When you used :root, the styles automatically got attached to HTML tag
Starting with Angular v9 you can use the style binding to change a value of a custom property
<app-component-name [style.--theme-color-1="'#CCC'"></app-component-name>
Some examples add variables directly to html tag and it seem in the element source as a long list. I hope this helps to you,
class AppComponent {
private variables=['--my-var: 123;', '--my-second-var: 345;'];
private addAsLink(): void {
const cssVariables = `:root{ ${this.variables.join('')}};
const blob = new Blob([cssVariables]);
const url = URL.createObjectURL(blob);
const cssElement = document.createElement('link');
cssElement.setAttribute('rel', 'stylesheet');
cssElement.setAttribute('type', 'text/css');
cssElement.setAttribute('href', url);
document.head.appendChild(cssElement);
}
}

How to prefix Bootstrap 4 classes to avoid css classes conflict

I am working on building small applications that will live in a website. The website that will host these applications may or may not be using a css framework. I Want to prefix all Bootstrap classes with my own unique prefix.
To avoid "ANY INSTANCE or CHANCE" of conflict I want to prefix all Bootstrap CSS classes with - let's say - "year19-" prefix. So, for example, all the col- classes would now be year19-col- and all the .btn classes would now become .year19-btn, .year19-btn-primary, etc...
I know if I use the sass theme, new classes, then we would get around some of that as we can create our own prefixes using the theming approach, but JS would still remain a source of conflict if two versions of the same framework live on the same page. There was a Github project for Bootstrap 3 with the namespacing feature where you could just add your prefix in the namespace variable then compile the entire code to a CSS and JS package. Bootstrap 4 doesn't seem to have that package yet.
Also, I don't want to wrap the project with a css class. That approach is fine for some things, but not the right approach. I wouldn't even call that namespace. That is just wrapping the classes.
year19-btn-primary {
then this would be whatever the code that already existed there before, not touched.}
I managed to get classes prefixed for Bootstrap 5.1.3. You'll need to make the following changes before compiling Bootstrap yourself. My full implementation is available here: https://github.com/Robpol86/sphinx-carousel/tree/85422a6d955024f5a39049c7c3a0271e1ee43ae4/bootstrap
package.json
"dependencies": {
"bootstrap": "5.1.3",
"postcss-prefix-selector": "1.15.0"
},
Here you'll want to add postcss-prefix-selector to make use of it in postcss.
postcss.config.js
'use strict'
const prefixer = require('postcss-prefix-selector')
const autoprefixer = require('autoprefixer')
const rtlcss = require('rtlcss')
module.exports = ctx => {
return {
map: ctx.file.dirname.includes('examples') ?
false :
{
inline: false,
annotation: true,
sourcesContent: true
},
plugins: [
prefixer({
prefix: 'scbs-', // ***REPLACE scbs- WITH YOUR PREFIX***
transform: function (prefix, selector) {
let newSelector = ''
for (let part of selector.split(/(?=[.])/g)) {
if (part.startsWith('.')) part = '.' + prefix + part.substring(1)
newSelector += part
}
return newSelector
},
}),
autoprefixer({
cascade: false
}),
ctx.env === 'RTL' ? rtlcss() : false,
]
}
}
This is where the CSS will be prefixed. I'm using postcss instead of just wrapping bootstrap.scss with a class/id selector so I can use the Bootstrap 5 carousel component on Bootstrap 4 webpages (which is my use case). This will replace https://github.com/twbs/bootstrap/blob/v5.1.3/build/postcss.config.js
rollup.config.js
// ...
const plugins = [
replace({ // ***COPY/PASTE FOR OTHER BOOTSTRAP COMPONENTS***
include: ['js/src/carousel.js'], // ***YOU MAY NEED TO REPLACE THIS PATH***
preventAssignment: true,
values: {
'CLASS_NAME_CAROUSEL': '"scbs-carousel"', // ***USE YOUR PREFIXES HERE***
'CLASS_NAME_ACTIVE': '"scbs-active"',
'CLASS_NAME_SLIDE': '"scbs-slide"',
'CLASS_NAME_END': '"scbs-carousel-item-end"',
'CLASS_NAME_START': '"scbs-carousel-item-start"',
'CLASS_NAME_NEXT': '"scbs-carousel-item-next"',
'CLASS_NAME_PREV': '"scbs-carousel-item-prev"',
'CLASS_NAME_POINTER_EVENT': '"scbs-pointer-event"',
'SELECTOR_ACTIVE': '".scbs-active"',
'SELECTOR_ACTIVE_ITEM': '".scbs-active.scbs-carousel-item"',
'SELECTOR_ITEM': '".scbs-carousel-item"',
'SELECTOR_ITEM_IMG': '".scbs-carousel-item img"',
'SELECTOR_NEXT_PREV': '".scbs-carousel-item-next, .scbs-carousel-item-prev"',
'SELECTOR_INDICATORS': '".scbs-carousel-indicators"',
}
}),
babel({
// Only transpile our source code
// ...
Lastly rollup replace plugin is used to add the prefixes in the compiled javascript file. I wasn't able to find a way to just prefix the consts so I had to resort to having the entire const replaced and hard-coded with the full class names. This means you'll need to do this for every Bootstrap component that you're including in your final build (for me I just need the carousel so it's not a big deal).

What is the idiomatic way to create styles for a Reason-React component that depend on props?

To learn reason and reason-react, I'm working on a simple “Things 2 Do” app (see source code on GitHub).
I have a TodoItem component that should be rendered with strike-through style when the item has been completed.
I try to solve this by creating a record with various styles, similar to CSS classes, one root style and one for completed items.
type style = {
root: ReactDOMRe.style,
completed: ReactDOMRe.style
};
let styles = {
root: ReactDOMRe.Style.make(), /* add root styles here */
completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};
If the prop completed is true, I combine the root style with the completed style, otherwise I just use the root, like this:
let style = styles.root;
let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;
This works, but it seems clunky, so I'm wondering: Is there a more elegant solution, e.g. using a variant and a switch statement?
What is the idiomatic way to create styles for a Reason-React component that depend on props?
Here is the full code of my component:
type item = {
id: int,
title: string,
completed: bool
};
type style = {
root: ReactDOMRe.style,
completed: ReactDOMRe.style
};
let str = ReasonReact.stringToElement;
let component = ReasonReact.statelessComponent("TodoItem");
let styles = {
root: ReactDOMRe.Style.make(), /* add root styles here */
completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};
let make = (~item: item, ~onToggle, _) => {
...component,
render: (_) => {
let style = styles.root;
let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;
<div style>
<input
_type="checkbox"
onChange=((_) => onToggle())
checked=(Js.Boolean.to_js_boolean(item.completed))
/>
<label> (str(item.title)) </label>
</div>
}
};
I don't think there's anything that can be called idiomatic yet. The area is quickly changing, and even I have some ideas of my own on how to improve it, but this is more or less how I do it now using bs-css:
module Styles = {
open Css;
let root = completed => style([
color(white),
opacity(completed ? 0.666 : 1.),
textDecoration(completed ? LineThrough : None)
]);
}
...
render: _self =>
<div className=Styles.root(item.completed)>
...
</div>
For now, the way I'm styling my component is OK. There is not really an idiomatic way for styling React components in Reason yet.
The Reason documentation has this to say:
Since CSS-in-JS is all the rage right now, we'll recommend our official pick soon. In the meantime, for inline styles, there's the ReactDOMRe.Style.make API

Resources