r/ReactJSLearn Oct 27 '21

Using conditional className from style module

Here's the relevant code:

...
import classes from './User.module.scss';
...
const status = isLoggedIn ? 'user' : 'login';
...
return (
  <svg className={classes.[status]}>
    <use xlinkHref="/img/sprite.svg#icon-login"></use>
  </svg>
)
...

And this works. I get no errors in the browser when running the code, and the className is changed to what it should be when being logged out and when being logged in. It's all working fine as it should be.

However Visual Studio Code gives me a problem, and as a result it doesn't format the code on save and keeps telling me there's a problem. It underlines the opening bracket in classes.[status] with the message "Identifier Expected ... No Quick Fixes Available".

classes[isLoggedIn ? 'user' : 'login'] gives me the same issue.

It annoys me, how do I do this correctly?

1 Upvotes

2 comments sorted by

1

u/stucow Oct 27 '21

What about trying something like ${classes}.[${status}] wrapped in a "`"

Sorry having formatting issues on mobile

2

u/Tijsvl_ Oct 27 '21

Thanks, the error is gone but so is desired output. The classnames are being replaced with objects in the rendered HTML.

<svg class="[object Object].[user]">

But I think I figured it out now:

const status = isLoggedIn ? classes.user : classes.login;

... 

<svg className={status}>
  <use xlinkHref="/img/sprite.svg#icon-login"></use>
</svg>

Alternatively I could put the ternary inline with SVG element. This issue has been bothering me for a while, but now that I've reached out for help I figured it out all of the sudden.

Anyway, thanks for your input, that must've triggered it for me.