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.


Related Query

More Query from same tag