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>
)
}
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'
You can use template literals ``
In your case it will look like that:
<span className={`tab ${this.state.signin ? "selected" : ""}`}>Sign In</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With