Reputation: 444
I have a component where style is applied in form of json and I need to override styles conditionally.
See style definitions:
const classes = {
txt: {
color: 'green',
...
},
txtBlue:{
color: 'blue',
..
},
};
See template:
<div style={classes.txt + (this.state.goBlue ? classes.txtBlue)}></div>
The + (this.state.goBlue ? classes.txtBlue)
I have written above is not working and it is just to show what I need to understand and make work.
When this.state.goBlue
is true, I want both classes.txt
and classes.txtBlue
to apply to the div
.
Thanks
Upvotes: 0
Views: 138
Reputation: 444
Found the solution!
By adding this to the render()
function:
const txtStyle =
this.state.goBlue ?
Object.assign({}, classes.txt, classes.txtBlue) :
Object.assign({}, classes.txt);
And this to the template:
<div style={txtStyle}></div>
I was able to achieve what I wanted.
Upvotes: 0
Reputation: 8936
You didn't use the ternary operator correctly, you can do something like this:
<div style={ this.state.goBlue ? { ...classes.txt, ...classes.txtBlue } : classes.txt }></div>
This will apply both styles if this.state.goBlue
is truthy, otherwise it will only apply classes.txt
.
Upvotes: 2