Dynamically build classnames in TailwindCss - reactjs

I am currently building a component library for my next project with TailwindCss, I just ran into a small issue when working on the Button component.
I'm passing in a prop like 'primary' or 'secondary' that matches a color I've specified in the tailwind.config.js then I want to assign that to the button component using Template literals like so: bg-${color}-500
<button
className={`
w-40 rounded-lg p-3 m-2 font-bold transition-all duration-100 border-2 active:scale-[0.98]
bg-${color}-500 `}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</button>
The class name comes through in the browser just fine, it shows bg-primary-500 in the DOM, but not in the applied styles tab.
The theming is configured like so:
theme: {
extend: {
colors: {
primary: {
500: '#B76B3F',
},
secondary: {
500: '#344055',
},
},
},
},
But it doesn't apply any styling. if I just add bg-primary-500 manually it works fine.
I'm honestly just wondering if this is because of the JIT compiler not picking dynamic classnames up or if I'm doing something wrong (or this is just NOT the way to work with tailWind).
Any help is welcome, thanks in advance!

So after finding out that this way of working is not recommended and that JIT doesn't support it (Thanks to the generous commenters). I have changed the approach to a more 'config' based approach.
Basically I define a const with the basic configuration for the different props and apply those to the component. It's a bit more maintenance work but it does the job.
Here is the example of a config. (Currently without typing) and up for some better refactoring but you'll get the idea.
const buttonConfig = {
// Colors
primary: {
bgColor: 'bg-primary-500',
color: 'text-white',
outline:
'border-primary-500 text-primary-500 bg-opacity-0 hover:bg-opacity-10',
},
secondary: {
bgColor: 'bg-secondary-500',
color: 'text-white',
outline:
'border-secondary-500 text-secondary-500 bg-opacity-0 hover:bg-opacity-10',
},
// Sizes
small: 'px-3 py-2',
medium: 'px-4 py-2',
large: 'px-5 py-2',
};
Then I just apply the styling like so:
<motion.button
whileTap={{ scale: 0.98 }}
className={`
rounded-lg font-bold transition-all duration-100 border-2 focus:outline-none
${buttonConfig[size]}
${outlined && buttonConfig[color].outline}
${buttonConfig[color].bgColor} ${buttonConfig[color].color}`}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</motion.button>

this way of writing Tailwind CSS classes is not recommended. Even JIT mode doesn't support it, to quote Tailwind CSS docs: "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"

EDIT: Better implementation 2022 - https://stackoverflow.com/a/73057959/11614995
Tailwind CSS does not support dynamic class names (see here). However, there's still a way to accomplish this. I needed to use dynamically build class names in my Vue3 application. See the code example below.
Upon build tailwind scanes your application for classes that are in use and automatically purges all other classes (see here). There is however a savelist feature that you can use to exclude classes from purging - aka they will always make it to production.
I have created a sample code below, that I use in my production. It combines each color and each color shade (colorValues array).
This array of class names is passed into the safelist. Please note, that by implementing this feature you ship more css data to production as well as ship css classes you may never use.
const colors = require('./node_modules/tailwindcss/colors');
const colorSaveList = [];
const extendedColors = {};
const colorValues = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
for (const key in colors) {
// To avoid tailWind "Color deprecated" warning
if (!['lightBlue', 'warmGray', 'trueGray', 'coolGray', 'blueGray'].includes(key))
{
extendedColors[key] = colors[key];
for(const colorValue in colorValues) {
colorSaveList.push(`text-${key}-${colorValue}`);
colorSaveList.push(`bg-${key}-${colorValue}`);
}
}
}
module.exports = {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}"
],
safelist: colorSaveList,
theme: {
extend: {
colors: extendedColors
}
},
plugins: [
require('tailwind-scrollbar'),
]
}

For tailwind JIT mode or v3 that uses JIT, you have to ensure that the file where you export the object styles is included in the content option in tailwind.config.js, e.g.
content: ["./src/styles/**/*.{html,js}"],

If someone comes across in 2022 - I took A. Mrózek's answer and made a couple of tweaks to avoid deprecated warnings and an issue with iterating non-object pallettes.
const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []
// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]
for (const colorName in tailwindColors) {
if (deprecated.includes(colorName)) {
continue
}
const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
const pallette = tailwindColors[colorName]
if (typeof pallette === "object") {
shades.forEach((shade) => {
if (shade in pallette) {
colorSafeList.push(`text-${colorName}-${shade}`)
colorSafeList.push(`bg-${colorName}-${shade}`)
}
})
}
}
// tailwind.config.js
module.exports = {
safelist: colorSafeList,
content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
colors: tailwindColors,
},
},
plugins: [],
}

this might be a bit late, but for the people bumping this thread.
the simplest explaination for this is;
Dynamic Class Name does not work unless you configured Safelisting for the Dynamic class name,
BUT, Dynamic Class works fine so long as its a full tailwind class name.
its stated here
this will not work
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
but this one works
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
its states;
As long as you always use complete class names in your code, Tailwind
will generate all of your CSS perfectly every time.
the longer explanation;
Tailwind will scan all the files specified in module.exports.content inside tailwind.config.js and look for tailwind classes, it does not even have to be in a class attribute and can even be added in commented lines, so long as the full class name is present in that file and class name is not dynamically constructed; Tailwind will pull the styling for that class,
so in your case, all you have to do is put in the full class name inside that file for all the possible values of your dynamic class
something like this
<button className={ color === 'primary' ? 'bg-primary-500' : 'bg-secondary-500'}>
{children}
</button>
or the method I would prefer
<!-- bg-primary-500 bg-secondary-500 -->
<button className={`bg-${color}-500 `}>
{children}
</button>
here's another example, although its Vue, the idea would be the same for any JS framework
<template>
<div :class="`bg-${color}-100 border-${color}-500 text-${color}-700 border-l-4 p-4`" role="alert">
test
</div>
</template>
<script>
/* all supported classes for color props
bg-red-100 border-red-500 text-red-700
bg-orange-100 border-orange-500 text-orange-700
bg-green-100 border-green-500 text-green-700
bg-blue-100 border-blue-500 text-blue-700
*/
export default {
name: 'Alert',
props: {
color: {type: String, default: 'red'}
}
}
</script>
and the result would be this
<Alert color="red"></Alert> <!-- this will have color related styling-->
<Alert color="orange"></Alert> <!-- this will have color related styling-->
<Alert color="green"></Alert> <!-- this will have color related styling-->
<Alert color="blue"></Alert> <!-- this will have color related styling-->
<Alert color="purple"></Alert> <!-- this will NOT have color related styling as the generated classes are not pre-specified inside the file -->

Now could use safeListing
and tailwind-safelist-generator package to "pregenerate" our dynamics styles.
With tailwind-safelist-generator, you can generate a safelist.txt file for your theme based on a set of patterns.
Tailwind's JIT mode scans your codebase for class names, and generates CSS based on what it finds. If a class name is not listed explicitly, like text-${error ? 'red' : 'green'}-500, Tailwind won't discover it. To ensure these utilities are generated, you can maintain a file that lists them explicitly, like a safelist.txt file in the root of your project.

In v3 as Blessing said you can change the content array to support that.
I had this
const PokemonTypeMap = {
ghost: {
classes: "bg-purple-900 text-white",
text: "fantasma",
},
normal: {
classes: "bg-gray-500 text-white",
text: "normal",
},
dark: {
classes: "bg-black text-white",
text: "siniestro",
},
psychic: {
classes: "bg-[#fc46aa] text-white",
text: "psíquico",
},
};
function PokemonType(props) {
const pokemonType = PokemonTypeMap[props.type];
return (
<span
className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans'] italic"}
>
{pokemonType.text}
</span>
);
}
export default PokemonType;
something similar to your approach, then I moved the array to a JSON file, it thought was working fine, but was browser caché... so following Blessing's response, you can add .json like this
content: ["./src/**/*.{js,jsx,ts,tsx,json}"],
Finally I have this code, it's better in my view.
import PokemonTypeMap from "./pokemonTypeMap.json";
function PokemonType(props) {
const pokemonType = PokemonTypeMap[props.type];
return (
<span className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans']"}>
{pokemonType.text}
</span>
);
}
export default PokemonType;

Is it recommended to use dynamic class in tailwind ?
No
Using dynamic classes in tailwind-css is usually not recommended because tailwind uses tree-shaking i.e any class that wasn't declared in your source files, won't be generated in the output file.
Hence it is always recommended to use full class names
According to Tailwind-css docs
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS
Isn't there work around ?
Yes
As a last resort, Tailwind offers Safelisting classes.
Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.
In your example,you want to have 100 500 700 shades of colors. You can use regular expressions to include all the colors you want using pattern and specify the shades accordingly .
Note: You can force Tailwind to create variants as well:
In tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
{
pattern: /bg-(red|green|blue|orange)-(100|500|700)/, // You can display all the colors that you need
variants: ['lg', 'hover', 'focus', 'lg:hover'], // Optional
},
],
// ...
}
EXTRA: How to automate to have all tailwind colors in the safelist
const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []
// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]
for (const colorName in tailwindColors) {
if (deprecated.includes(colorName)) {
continue
}
// Define all of your desired shades
const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
const pallette = tailwindColors[colorName]
if (typeof pallette === "object") {
shades.forEach((shade) => {
if (shade in pallette) {
// colorSafeList.push(`text-${colorName}-${shade}`) <-- You can add different colored text as well
colorSafeList.push(`bg-${colorName}-${shade}`)
}
})
}
}
// tailwind.config.js
module.exports = {
safelist: colorSafeList, // <-- add the safelist here
content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
colors: tailwindColors,
},
},
plugins: [],
}
Note: I have tried to summarize the answer in all possible ways, In the combination of all possible answers.Hope it helps

I had a similar issue, instead of passing all the possible configs, I just pass the data to the style property of the HTML. This is far more efficient!
or
Pass a class name as a prop and let the user of the package write the styles to that class.
const CustomComp = ({
keyColGap = 0,
keyRowGap = 0,
className = '',
}: Props) => {
const classNameToRender = (): string => {
return `m-1 flex flex-col ${className}`.trim();
};
const rowStylesToRender = (): React.CSSProperties | undefined => {
const styles: React.CSSProperties | undefined = { gap: `${keyRowGap}rem` };
return styles;
};
const colStylesToRender = (): React.CSSProperties | undefined => {
const styles: React.CSSProperties | undefined = { gap: `${keyColGap}rem` };
return styles;
};
return (
<div className={classNameToRender()} style={rowStylesToRender()}>
{layout.map((row) => {
return (
<div
className={`flex justify-around`}
style={colStylesToRender()}
key={row}
>
/* Some Code */
</div>
);
})}
</div>
}

Related

How to change color of month/year label of material-ui datepicker in react using createMuiTheme?

I want to change the color of the label circled here:
How would I go about doing so?
I have tried changing the color of the primary colors on the palette. Also, there does not seem to be a way to do it through CSS without affecting other components.
Here's my current code for the theme:
const calendarTheme = createMuiTheme({
overrides: {
MuiPickersDay: {
day: {
color: "#436E70",
},
daySelected: {
backgroundColor: "#436E70",
},
dayDisabled: {
color: "#436E70",
},
current: {
color: "#436E70",
},
},
},
});
Material-UI pickers v3.3.10
https://material-ui-pickers.dev/guides/css-overrides
Variant: static
Npm package used: #material-ui/pickers
Someone suggested this post: Change header color of Material-UI Date Picker
That solution is 5+ years old already,getMuiTheme is not part of v3.3.10. Also the way described in that post does not work anymore, it does not matter where in the createMuiTheme object I put
datePicker: {
color: palette.primary1Color,
textColor: palette.alternateTextColor,
calendarTextColor: palette.textColor,
selectColor: palette.primary2Color,
selectTextColor: palette.alternateTextColor,
calendarYearBackgroundColor: palette.canvasColor,
headerColor: palette.pickerHeaderColor || palette.primary1Color,
},
It does not work, it doesn't have any effects. And the documentation also doesn't bring much light to the case.
Thanks in advance.
According to the documentation from your link the datepicker has a rule (sometimes called slot) called MuiPickersCalendarHeader. This rule is used to provide styling to a <div> tag that is an ancestor to the <p> tag that contains the text you've circled in your sample image (i.e. "July 2022"). You can see how these tags are structured in the Inspector tab of the Developer Tools Window in Firefox (in the browser highlight the text "July 2022", right-click the highlighted text, then from the context menu choose Inspect). Knowing the tag structure, we can apply a CSS selector to target the <p> tag like so:
const calendarTheme = createMuiTheme({
overrides: {
MuiPickersDay: {
...
// MuiPickersCalendarHeader rule
MuiPickersCalendarHeader: {
switchHeader: {
['& > div > p']: {
// backgroundColor: lightBlue.A200,
// color: "white",
},
},
},
...
}
}
The above code is untested. If you have problems with it say so in a comment, and I'll try to test it.

Types for tailwind

I am using tailwind.config.js in order to extend some colors:
const theme = {
mode: 'jit',
content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'],
darkMode: 'media', // 'media' or 'class'
theme: {
extend: {
colors: {}
but then I might pass a color to a component in props in order to later use it as border-${color} and/or text-${color}.
Right now the value would be just of type string so I am not getting the tips, is there some way to get a type of the combined custom colors + default tailwind's colors ?
You have to return the complete string border-red-500 in place of border-${color}.
Like you can define a function like this
let {color} = props;
function getColor( color) {
return 'border-" + color;
}
And then use it like this
<div className={`border-2 ${getColor}`}> hello world </div>

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.

How to make custom theme using Shoutem's StyleProvider that properly uses underlying INCLUDE

I really love the shoutem theme library, but I'm finding it difficult to hook into the recursive INCLUDE that makes the underlying code work beautifully (See code+documentation here: https://github.com/shoutem/theme/blob/develop/src/Theme.js). For instance, if we have:
render() {
return (
<StyleProvider style={theme}>
<View />
</StyleProvider>
);
}
const theme = _.merge(getTheme(), {
'shoutem.ui.Text': {
color: 'green',
},
});
This simple text color change will work, but only for shoutem Text components. However, Heading, Title, Subtitle, etc. all of which pull from Text attributes in the shoutem library because of INCLUDE. The use of a simple _.merge(...) only overwrites the component itself, but not anything that it might subsequently affects. It sounds like I need to overwrite attributes higher up in the tree (e.g., Text), and then regenerate the theme so it affects all "children" that it's included in (e.g., Heading and Title). Using the publicly exposed API, is this possible to do somehow at the moment? Or are there any forks or utilities you're aware of that accomplish this with your library.
There is a text property in the root of the default shoutem ui theme that is included into all text elements (https://github.com/shoutem/ui/blob/develop/theme.js#L292). You should be able to accomplish your use case by simply overriding values from that property:
const theme = _.merge(getTheme(), {
text: {
color: 'green',
},
});
In case you want to create a more complex theme, you can use INCLUDE in your code as well. INCLUDE works by merging all values from top level theme properties it targets. You can use it to include properties from the base theme, and you can also include your own custom properties:
import { INCLUDE } from '#shoutem/theme';
const theme = _.merge(getTheme(), {
// Define a top level property to use in includes
largeText: {
fontSize: 20,
},
'shoutem.ui.Text': {
// Include a text property from the base theme
// and a largeText property defined above
[INCLUDE]: ['text', 'largeText'],
// Override the text color after all includes
// have been resolved
color: 'green',
},
});
Sometimes specific components define styles after INCLUDEs have been resolved, those styles have a higher priority, and will always override the style from INCLUDEs. To change those styles, you can use a createSharedStyle helper:
import { createSharedStyle } from '#shoutem/theme';
const textComponents = [
'shoutem.ui.Heading',
'shoutem.ui.Title',
'shoutem.ui.Subtitle',
'shoutem.ui.Text',
'shoutem.ui.Caption',
];
const theme = _.merge(getTheme(), {
...createSharedStyle(textComponents, {
color: 'green',
},
});
Finally, some more basic customizations can be done through theme variables, you can pass custom variables when calling getTheme(https://github.com/shoutem/ui/blob/develop/theme.js#L55-L144).

Platform conditional statements in stylesheets (react-native)

For minor platform specific code you can use the Platform module to execute some platform dependent code. As detailed in the docs here:
https://facebook.github.io/react-native/docs/platform-specific-code.html
There is an example of how to use it in stylesheets
var styles = StyleSheet.create({
height: (Platform.OS === 'ios') ? 200 : 100,
});
I would like to do something similar but a simple if statement to decide whether or not to use a style, for example one that is for one platform only.
Here is an example:
var styles = StyleSheet.create({
textInputStyle: {
if (Platform.OS === 'android') {
textAlignVertical:'top' // android only style
}
}
});~
This is syntactically incorrect, what's the correct code to achieve this. I would like to avoid having two separate style sheets for each Platform as it seems unnecessary when it's only 1 or 2 fields that are different.
I believe this is what you are looking for:
var styles = StyleSheet.create({
textInputStyle: {
...Platform.select({
ios: {
//
},
android: {
//
},
}),
}
})
The link you provided shows the above code as an example. (v0.59)
Please have a look on react-native-extended-stylesheet that supports media queries allowing you to define styles for particular platform / screen.
For example:
import EStyleSheet from 'react-native-extended-stylesheet';
...
render() {
return (
<View style={styles.column}></View>
);
}
...
const styles = EStyleSheet.create({
'#media ios': {
column: {
width: '80%'
}
},
'#media android': {
column: {
width: '90%'
}
}
});
You can also use it for particular style items:
const styles = EStyleSheet.create({
column: {
'#media ios': {
width: '80%'
},
'#media android': {
width: '90%'
}
}
});
One way to achieve is to have both different styles and then apply it dynamically in render. For ex:
render(){
let platformStyle = Platform.OS === 'ios' ? styles.iosStyle: styles.androidStyle;
return (<View style={platformStyle}>
.....
</View>);
}
.....
const styles = StyleSheet.create({
iosStyle: {
},
androidStyle: {
}
});
I had the same problem with medium-sized RN app than you have.
Currently, I have external stylesheets for both iOS and Android (Layout.ios.js and Layout.android.js) which I import to components. This is meant for basic styling of components and it's not as hard to maintain as it sounds.
There are several minor issues on Android (e.g. lineHeight in some cases causes red screen of death). And that's why I had to implement this approach and I've been happy with it.
Besides most of the components share common styling, so external stylesheet works perfectly in that case too.
But in cases I have only minor difference, I do it locally, e.g.
header: {
marginTop: (Platform.OS === 'ios') ? 20 : 15
}
I've tried to look for alternative approaches, but at the moment this seems to be the way of doing it.
In addition, textAlignVertical is just ignored by iOS, so you don't need to wrap it with Platform check.

Resources