Kuan
Kuan

Reputation: 11389

Dynamic class in react.js

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>
    )
}

Upvotes: 5

Views: 4485

Answers (3)

Tushar Sharma
Tushar Sharma

Reputation: 302

Though John's answer does the Job. That library lacks function support for determining the value.

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})} />

Upvotes: 0

John Ruddell
John Ruddell

Reputation: 25842

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' 

Upvotes: 4

jmac
jmac

Reputation: 706

You can use template literals ``

In your case it will look like that:

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

Upvotes: 4

Related Questions