Patricio Vargas
Patricio Vargas

Reputation: 5522

Conditionally add class in render not working - React/Gatsby

I have this component:

const imageDisplay = false;
  ...
    <PostsGrid
       posts={filteredPosts}
       defaultCoverImage={defaultCoverImage}
       imageDisplay={imageDisplay}
    />

PostGrid.js

...
console.log(imageDisplay)// prints false

    <Img
         className={'cover-image' + imageDisplay ? 'show' : 'hide'}
         fluid={
                post.coverImage
                ? post.coverImage.fluid
                : defaultCoverImage.fluid
                }
                alt={post.title}
          />

This should add the class hide, but it doesn't. If I flip it, the hide gets added but now the show doesn't get added if I change the imageDisplay variable to true:

className={'cover-image' + !imageDisplay ? 'hide' : 'show'} 

Upvotes: 1

Views: 473

Answers (2)

Andris Laduzans
Andris Laduzans

Reputation: 458

i would suggest getting used to string interpolations in your example you could do something like this

className={`cover-image ${imageDisplay? 'show': 'hide'}`}

also shouldn't your example just put both classes together causing invalid 'cover-imageshow' OR 'cover-imagehide' ? maybe that is the issue causing error

Upvotes: 1

n3ko
n3ko

Reputation: 415

Its because the operator precedence. You should use parentheses. Just look at the below:

imageDisplay = false
console.log('cover-image' + !imageDisplay ? 'hide' : 'show')

imageDisplay = true
console.log('cover-image' + !imageDisplay ? 'hide' : 'show')

imageDisplay = false
console.log('cover-image' + (!imageDisplay ? 'hide' : 'show'))

imageDisplay = true
console.log('cover-image' + (imageDisplay ? 'hide' : 'show'))

I'm not sure, but you probably not want to change the classname, but add another class. For this you will need a space between the classnames.

I also suggest also to avoid the ternary operator if you can. Its possible with libraries like classnames and your code gets a little cleaner.

Upvotes: 2

Related Questions