M.Imran Mamda
M.Imran Mamda

Reputation: 444

Apply style conditionally on a React component with json-style definitions

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

Answers (2)

M.Imran Mamda
M.Imran Mamda

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

Matt Aft
Matt Aft

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

Related Questions