0

Came across this when creating an animated dropdown for a navbar.

In a strict React implementation, an inline if/else statement can be used with an onClick toggle to set and remove CSS animation styles. In order to provide a default styling (with no animation) for when state is null, a class can be added before the inline if/else operation:

<div className={`navbar ${reactState ? "expanded" : "collapsed"}`}>

How do I replicate this in NextJS?

I can't find anything in the documentation and have blindly attempted the following (unsuccessfully):

<div className={styles.navbar (reactState ? `${styles.expanded}` : `${styles.collapsed}`)}>
<div className={styles.navbar [reactState ? `${styles.expanded}` : `${styles.collapsed}`]}>
<div className={styles.navbar `${reactState ? `${styles.expanded}` : `${styles.collapsed}`}`}>

The only success I've had is with the following, which seems like overkill:

<div className={
  reactState != null ?
    (reactState ? `${styles.navbar} ${styles.expanded}` 
    : `${styles.navbar} ${styles.collapsed}`)
  : styles.navbar
}>

I'm clearly not fully understanding how NextJS handles React styling. Any help would be appreciated.

2
  • 1
    It works exactly the same as in normal React, see the docs. But you have got an error with your string interpolation, you'll see the missing spaces if you open up the dev tools. E.g. ` ${styles.expanded} ` --> styles.expanded Commented Aug 13, 2022 at 15:50
  • Can you please tell me, How you imported the CSS file. I will guide you to solve this issue. Commented Aug 13, 2022 at 16:22

1 Answer 1

1

This should work, and it works as same as React. Only you didn't escape the values correctly.

<div className={`${styles.navbar} ${reactState ? styles.expanded : styles.collapsed}`}>...</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.