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 do I group objects by key and modify the array the reduce function returns?
- Failed to load resource: the server responded with a status of 500. Deployed react app with vercel
- How to do simple ternary in React with TypeScript?
- CSS transition - Disappear and appear again
- Delete item from list not rendering react js
- React and Jest: How to mock implementation of member function
- Different IP addresses in production and test environment how to handle it automaticaly
- can't type in text field after adding onChange react typescript
- How to remove nested collection from mongodb using mongoose?
- Update value with user input
- How does PureComponent work?
- Cant turn on switch inside Material-Table
- Sending object to JS function not working for some reason
- map is not a function on array React
- Django & React: Connecting multiple apps from one template
- Passing {ClassName} vs passing {<ClassName>} as react component porps. What is the difference?
- How to submit search fields after enter press
- graphQL: how to get an object from a list of objects, in a query
- In React, when using map() to loop through an array of elements, does the result need to only be displayed using the <ul> and <li> tags?
- ReactJs - Expected an assignment or function call and instead saw an expression
- Align Title Left React Chart.js V2
- How to display multiple selected values from a dropdown in React
- Flex cards in 5 column
- django-cors-header not working as expected when using Postman
- How to add ::-webkit-scrollbar pseudo element in Chakra UI element? (React)
- onChange is not working in react functional component while changing the value through state update
- How to conditionally show element in react JSX?
- Why is the `MouseEvent` in the checkbox event handler not generic?
- How to use an Electron <webview> tag in TypeScript?
- How to Implement Price Increase and Decrease Sorting in React Redux Application?