Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic class in react.js

Tags:

reactjs

All:

I wonder if I made a signin/signup toggle tab component, how can I dynamically add a selected class to according component(like 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>
    )
}
like image 296
Kuan Avatar asked May 02 '17 22:05

Kuan


2 Answers

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

usage

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

when invoking the 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 consistently in the order of default string, conditionals. just for the sake of readability for me and others that come by, its easy when you expect it to be the same.

you can pass it a lot of different things and it handles it. From the NPM docs

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' 
like image 73
John Ruddell Avatar answered Sep 24 '22 15:09

John Ruddell


You can use template literals ``

In your case it will look like that:

<span className={`tab ${this.state.signin ? "selected" : ""}`}>Sign In</span>
like image 27
jmac Avatar answered Sep 23 '22 15:09

jmac