Dynamic class in react.js

All:

I wonder if I made the signin / signup tab component to switch, how can I dynamically add the selected class to the corresponding component (e.g. ngclass)?

render(){
return (
            <div>
                <span className="tab" className={{"selected": this.state.signin}}>Sign In</span>
                <span className="tab" className={{"selected": !this.state.signin}}>Sign Up</span>
            </div>
    )
}
+4
source share
3 answers

I would recommend you use the classnames library , it is a very good and useful tool.

Using

import cx from 'classnames';
...
<span className={cx('tab', {selected: this.state.signin})}>Sign In</span>

when calling a function, you can pass default values ​​and an object to conditionally add classes in any order.

syntax: cx(default, {conditional: boolean, conditional: boolean});
syntax: cx({conditional: boolean, conditional: boolean}, default);
syntax: cx(something, {conditional: boolean}, 'something', 'something');

I prefer to use it sequentially in the order of the default string, conditional expressions. just for the convenience of reading and the others that come are easy when you expect it to be the same.

, . NPM

classNames('foo', 'bar'); // => 'foo bar' 
classNames('foo', { bar: true }); // => 'foo bar' 
classNames({ 'foo-bar': true }); // => 'foo-bar' 
classNames({ 'foo-bar': false }); // => '' 
classNames({ foo: true }, { bar: true }); // => 'foo bar' 
classNames({ foo: true, bar: true }); // => 'foo bar' 

// lots of arguments of various types 
classNames('foo', { bar: true, duck: false }, 'baz', { quux: true }); // => 'foo bar baz quux' 

// other falsy values are just ignored 
classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' 
+4

``

:

<span className={`tab ${this.state.signin ? "selected" : ""}`}>Sign In</span>
+2

Although John's answer is fulfilled by Job. This library lacks a support function to determine the value.

You can use this npm package. It handles everything and has parameters for static and dynamic classes based on a variable or 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})} />
0
source

Source: https://habr.com/ru/post/1676203/


All Articles