score:0
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"
score:0
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.
score:0
[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 : ""}`}>
score:1
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';
score:2
getBadgeClasses() {
let classes = "badge m-2 ";
classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
return classes;
}
<span className={this.getBadgeClasses()}>Total Count</span>
score:3
You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.
// Support for string arguments
getClassNames('class1', 'class2');
// support for Object
getClassNames({class1: true, class2 : false});
// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], {
class5 : function() { return false; },
class6 : function() { return true; }
});
<div className={getClassNames({class1: true, class2 : false})} />
score:3
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>
)
score:7
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" : "")'}>
score:8
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
}));
}
score:13
Don't think of a solution so complicated.
here is the easiest solution for your problem.
<div className={`wrapper searchDiv ${this.state.something}`}>
...
</div>
score:44
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"
}
score:48
A simple possible syntax will be:
<div className={`wrapper searchDiv ${this.state.something}`}>
score:69
Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnames utility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.
So as an example from its React documentation:
render () {
var btnClass = classNames({
'btn': true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>I'm a button!</button>;
}
Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.
score:341
You can either do this, normal JavaScript:
className={'wrapper searchDiv ' + this.state.something}
or the string template version, with backticks:
className={`wrapper searchDiv ${this.state.something}`}
Both types are of course just JavaScript, but the first pattern is the traditional kind.
Anyway, in JSX, anything enclosed in curly brackets is executed as JavaScript, so you can basically do whatever you want there. But combining JSX strings and curly brackets is a no-go for attributes.
Source: stackoverflow.com
Related Query
- How to dynamically add a class to manual class names?
- How to dynamically add and remove class on click with React?
- How to dynamically add class to parent div of focused input field?
- How to dynamically add class in react?
- How to add class name dynamically in react JS on selected tab
- How to dynamically add a CSS class to a div in a component
- How to add a class with React.js?
- How to add "refs" dynamically with react hooks?
- How to add a dynamic class to body tag in Gatsby.js?
- How to add class in element on scroll React js
- When, where and how to add class to the document.body when using React.js
- How to hash CSS class names in Nextjs?
- How do I dynamically add an array to a react-bootstrap table?
- How to add components to list dynamically in React with no redundant render?
- How do you add !important to a CSS-in-JS (JSS) class property?
- How to add active class to clicked item in ReactJS
- How reliable are MUI Global Class names in JSS?
- How to add next-i18next translation on a dynamically routed page in a nextjs application?
- How to add and remove add class for list in reactjs?
- How to execute appropriate useState dynamically from string names in react hooks?
- How to add a CSS class to an element on click - React
- How to add new props dynamically to the component using navigator in React Native
- How To Add More component dynamically React Native
- How to add slick-active class in Slider dots in React Slick
- How to dynamically add css style to pseudo classes in React
- REACT.JS: How to loop over all NavBar buttons and remove their class and add "active" class to the clicked button
- How to add elements dynamically using redux
- How to add and remove table rows Dynamically in React.js
- How to add a onclick event in ag-grid cell renderer reactjs and access the class function
- How to add style or class name and remove other element from web component?
More Query from same tag
- How to map array into Avatar Element
- How can I limit the number of characters per line in a textArea using React?
- How to maintain a focus on Input field when popper is shown in Material-ui
- How to get a form to disapear upon submission in React
- Force TextField with type number to display dot as decimal separator
- Webpack check file exist and import in condition
- How do I create an event that Formik's handleChange will like?
- How do v call the render function of a class from a function of another class in ReactJS?
- Prompt with callback when user tries to exit
- union types not being recognised in React
- Uncaught ReferenceError: Searchbar is not defined
- How to subscribe to a Redux action in a React component
- setTimeout function not executing at specific time given in react app
- webpack production build not working
- Await API calls before render private route
- how to use json objects from request
- Countdown-Flipclock JS React.js | How to compare a variable(prop) to the same variable 1s ago?
- Include multiple components and <div> in if statement in React
- React error: TypeError: render is not a function
- JSON.stringify() function is replacing the file object with an empty one
- Is there a way to put requirements on hook dependencies?
- React useEffect and Axios: Making chained API calls within 'then'
- API request error - No 'Access-Control-Allow-Origin' header is present on the requested resource
- what is wrong in this code that made for validating a input field
- Conditionally render <td> in a React component
- How do I toggle sidebar on React
- react-select change menu height
- Turning eslint rule off in eslintrc.json
- Randomly set an element's top property based on parent height on render
- How to maintain the visibility of Tooltip after closing a form in React JS