I\'m doing some React right now and I was wondering if there is a \"correct\" way to do conditional styling. In the tutorial they use
style={{
textDecorati
If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:
style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
In case 'someCondition' not fulfilled then you pass empty object.
You can use somthing like this.
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).
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'
Another way, using inline style and the spread operator
style={{
...completed ? { textDecoration: completed } : {}
}}
That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.