Apply style conditionally on a React component with json-style definitions - reactjs

I have a component where style is applied in form of json and I need to override styles conditionally.
See style definitions:
const classes = {
txt: {
color: 'green',
...
},
txtBlue:{
color: 'blue',
..
},
};
See template:
<div style={classes.txt + (this.state.goBlue ? classes.txtBlue)}></div>
The + (this.state.goBlue ? classes.txtBlue) I have written above is not working and it is just to show what I need to understand and make work.
When this.state.goBlue is true, I want both classes.txt and classes.txtBlue to apply to the div.
Thanks

You didn't use the ternary operator correctly, you can do something like this:
<div style={ this.state.goBlue ? { ...classes.txt, ...classes.txtBlue } : classes.txt }></div>
This will apply both styles if this.state.goBlue is truthy, otherwise it will only apply classes.txt.

Found the solution!
By adding this to the render() function:
const txtStyle =
this.state.goBlue ?
Object.assign({}, classes.txt, classes.txtBlue) :
Object.assign({}, classes.txt);
And this to the template:
<div style={txtStyle}></div>
I was able to achieve what I wanted.

Related

Dynamically build classnames in TailwindCss

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>
}

React - how to add fontsize into React.createElement?

Am a little of a newbie on the block and learning React - I have this segment of a function below:
AlertNotifications.prototype.render = function () {
return (React.createElement("div", null, this.props.alerts.map(function (alert) { return React.createElement(MessageBar, { messageBarType: alert.type === AlertType.Urgent ? MessageBarType.severeWarning : MessageBarType.warning, isMultiline: false },
alert.message,
alert.moreInformationUrl ? React.createElement("a", { href: alert.moreInformationUrl }, strings.MoreInformation) : ''); })));
};
return AlertNotifications;
I need to alter the fontsize of the returned DIV - can you please let me know what I need to alter - or add to the above to alter the fontsize to Arial 16px?
Many thanks in advance
G
Try to use this one:
React.createElement("div", {
style: {
"font-size": "16px"
}
}, /* Put here what you need to insert in div */)
So, basically, the second attribute in React.createElement is used for attributes.
You can add a class and style it.
React.createElement('div', {class-here}, .......)

Vue - Update rendered elements from a v-for with :style that uses their values [duplicate]

I'm looping through elements and I'm positioning div using top and left CSS properties:
<div
v-for="coord in coords"
:style="{ top: coord.y + 'px', left: coord.x + 'px' }"
></div>
Sometimes instead of top property I need to use bottom (this depends on one of my Vuex store values). How can I dynamically define if I should use top or bottom CSS property?
I tried to used computed prop isTopOrBottom which would return 'top' or 'bottom: :style="{ isTopOrBottom: coord.y + 'px', left: coord.x + 'px' }". But this is not working in Vue.
You can use the ternary operator (in case computed properties are not working)
For example:
<span
class="description"
:class="darkMode ? 'dark-theme' : 'light-theme'"
>
Hope this help.
It should be like JavaScript string concatenation
<div
v-for="coord in coords"
:style="'top: '+coord.y + 'px;left: '+coord.x + 'px'"
></div>
Vue.config.productionTip = false;
Vue.config.devtools=false;
var app = new Vue({
el: '#app',
data:{
coords:[{y:10,x:10},{y:20,x:20},{y:30,x:30}]
}
});
.border-line{
border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
<div class="border-line"
v-for="coord in coords"
:style="'margin-top: '+coord.y + 'px;margin-left: '+coord.x + 'px'"
>Test</div>
</div>
You could do something like this:
:class="{ is-top: isTop, is-bottom: isBottom }"
And in your script:
computed() {
isTop() {
// return top condition
},
isBottom() {
// return bottom condition
}
}
Handle css:
.is-top {
...
}
.is-bottom {
...
}
You can also use a Vuejs custom directive for this! https://v2.vuejs.org/v2/guide/custom-directive.html
Check this out:
In your template:
<p v-position="expressionThatMakesItTop" v-if="isSignedIn">Welcome back {{user.email}}</p>
If you want to register a directive locally, components also accept a directives option, check that out on the documentation I linked.
I am going to show you how to do it globally so in your main.js file, before constructing the Vue instance of course:
I left the console.log that displays the objects that you can use in your directive so you can explore them on your console and tailor this to your needs.
Vue.directive("position", {
bind: function(el, binding, vnode) {
console.log(el, binding, vnode);
el.style.left = `${vnode.context.coord.x}px`;
if (binding.value) {
el.style.top = `${vnode.context.coord.y}px`;
return;
}
el.style.bottom = `${vnode.context.coord.y}px`;
}
});

change text color from directive when innerHTML matches

I have a page where I am rendering many columns with the help of the ng-repeat.
HTML
<div ng-repeat="col in selectedColumn" class="cellHldr ng-status-color">{{lead[col.name]}}</div>
Now I have made a directive ngStatusColor
.directive('ngStatusColor', function () {
return {
restrict: "C",
compile: function (tElement, tAttributes) {
return {
post: function postLink( scope, element, attributes ) {
console.log("element",element[0].innerHTML );
if(element[0].innerHTML=='Open'){
console.log("hellooo");
}
}
}
}
}
});
I need to color the text of that column which has the {{lead[col.name]}}like 'open','closed'. Rest should be left as it is
Since you are going the innerHtml way , you can just add a font tag to the inner html to change the color :
if(element[0].innerHTML=='Open'){
element[0].innerHTML="<font color='red'>"+element[0].innerHTML+"</font>";
}
The angular way to do this would be using ng-class.On your div which put the following :
ng-class="{ 'red': lead[col.name]=='Open', blue: lead[col.name]=='close' }"
And create two css classes red and blue:
.red {
color: red;
}
.blue {
color: blue;
}
What this will do this is when it will assign red class to your element if the value of lead[col.name] becomes 'Open' , Blue if 'Close'.
If you want to get more info about ng-class , I would recommend you to go through this link :ng-class uses
Use ng-class for the same.
CSS
.colorChange {
color: green;
}
HTML
<div ng-repeat="col in selectedColumn" class="cellHldr ng-status-color" ng-class="lead[col.name] === 'open' ? 'colorChange': 'normalStyle'">{{lead[col.name]}}</div>
Will this approach work ?
if(element[0].innerHTML=='Open'){
element[0].style.color = "red";
}

Add inline style in reactjs without using JSX

I am trying to add inline style to the element using reactjs. I found
var divStyle = {
color: 'white',
backgroundImage: 'url(' + imgUrl + ')'
};
ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);
in reactjs docs. Thing is, it is not working without JSX.
I tried doing this.
return (
React.DOM.div({ className: 'eventsOuter'},
{style:'divStyle'}
)
But the style part is not working.
Is there any way to fix this?
You need to pass variable instead of variable name:
React.DOM.div({
className: 'eventsOuter',
style: divStyle
}, 'Hello World!')
Also you can compile online:
on the babel website

Resources