I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:
<div className="wrapper searchDiv {this.state.something}">
...
</div>
Any ideas?
I need to add a dynamic class to a list of regular classes, but have no idea how (I'm using babel), something like this:
<div className="wrapper searchDiv {this.state.something}">
...
</div>
Any ideas?
A simple possible syntax will be:
<div className={`wrapper searchDiv ${this.state.something}`}>
Here is the Best Option for Dynamic className , just do some concatenation like we do in Javascript.
className={
"badge " +
(this.state.value ? "badge-primary " : "badge-danger ") +
" m-4"
}
Don't think of a solution so complicated.
here is the easiest solution for your problem.
<div className={`wrapper searchDiv ${this.state.something}`}>
...
</div>
try this using hooks:
const [dynamicClasses, setDynamicClasses] = React.useState([
"dynamicClass1", "dynamicClass2"
]);
and add this in className attribute :
<div className=`wrapper searchDiv ${[...dynamicClasses]}`>
...
</div>
to add class :
const addClass = newClass => {
setDynamicClasses([...dynamicClasses, newClass])
}
to delete class :
const deleteClass= classToDelete => {
setDynamicClasses(dynamicClasses.filter(class = > {
class !== classToDelete
}));
}
If you need style names which should appear according to the state condition, I prefer to use this construction:
<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>
If you're using css modules this is what worked for me.
const [condition, setCondition] = useState(false);
\\ toggle condition
return (
<span className={`${styles.always} ${(condition ? styles.sometimes : '')`}>
</span>
)
getBadgeClasses() {
let classes = "badge m-2 ";
classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
return classes;
}
<span className={this.getBadgeClasses()}>Total Count</span>
[UPDATED Apr-21 2022: Adding curly brackets before and after backticks to prevent error]
you can simply use the condition for applying the specific class you want
<div className={`wrapper searchDiv ${this.state.something ? "class that you want" : ""}`}>
if you want to use the class of makeStyle you can use it like
<div className={`wrapper searchDiv ${this.state.something ? classes.specifiedClass : ""}`}>
className={css(styles.mainDiv, 'subContainer')}
This solution is tried and tested in React SPFx.
Also add import statement :
import { css } from 'office-ui-fabric-react/lib/Utilities';
const ClassToggleFC= () =>{
const [isClass, setClass] = useState(false);
const toggle =() => {
setClass( prevState => !prevState)
}
return(
<>
<h1 className={ isClass ? "heading" : ""}> Hiii There </h1>
<button onClick={toggle}>Toggle</button>
</>
)
}
I simply created a Function Component. Inside I take a state and set initial value is false..
I have a button for toggling state..
Whenever we change state rerender component and if state value (isClass) is false h1's className should be "" and if state value (isClass) is true h1's className is "heading"
Even though all of the answers above are quite good, the one that caught my attention is the string interpolation solution. So I'd like to propose a different approach to that using a custom StringBuilder.
Here's the implementation.
class StringBuilder {
static Builder() {
class Builder {
constructor() {
this.bucket = [];
}
append(str) {
if (str !== null) {
this.bucket.push(str);
}
return this;
}
build() {
return this.bucket.join(' ');
}
}
return new Builder();
}
}
Then you would just use it like this within a component.
const Field = (props) => {
const { label } = props;
const [hasFocus, setFocus] = useState(false);
const labelClasses = new StringBuilder.Builder()
.append('form-control')
.append(hasFocus ? 'has-focus' : null)
.build();
const turnOnFocus = () => setFocus(true);
const turnOffFocus = () => setFocus(false);
return (
<div onClick={turnOnFocus} onBlur={turnOffFocus} className="form-group">
<input
type="text"
defaultValue=""
onChange={setValue}
/>
<label className={labelClasses}>{label}</label>
</div>
);
};
In general, if you have more elements that require dynamic CSS classes, you could just instantiate another builder for that particular element. Additionally, if the class appears in more than one element with the same logic, then the solution would be extracting that logic to a method or function.
A word of caution to those that are using back ticks or concatenation for className in React: You need to have spaces between your class names. Without them, you have a long word that doesn't match any of your css.