Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Setting a (tricky) active class on react tabs

I have some very basic react tabs:

  const tabItems = ['Tab 1', 'Tab 2'];

  function TabGroup() {
    const [activeItem, setActive] = useState(tabItems[0]);
    return (
      <>      
        <div className={styles.tabs}>
          {tabItems.map(tabItem => (
            <button
              className={activeItem === tabItem ? "on" : "off"}
              onClick={() => setActive(tabItem)}
            >
              {tabItem}
            </button>
          ))}
        </div>
        <p>Active Tab: {activeItem} </p>
      </>
    );
  }

Which works fine, but our project uses modules for the CSS, imported like so at the top of the file:

import styles from 'styles/wallet.module.scss'

Calling a CSS class from the wallet.module.scss means you have to reference them like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div className={styles.foo}></div>

So my question is… back to the original example of my tabs, I need the className for the activeItem to take something like {styles.on} e.g.;

        <button
          className={activeItem === tabItem ? {styles.on} : {styles.off}}
          onClick={() => setActive(tabItem)}
        >

But calling them like that inside the activeItem == tabItem check throws an error:

./components/wallet.js
Error: 
  x Unexpected token `.`. Expected ... , *,  (, [, :, , ?, = or an identifier
    ,----
 24 | className={activeItem === tabItem ? {styles.on} : {styles.off}}
    :                                            ^
    `----

Caused by:
    0: failed to process input file
    1: Syntax Error

I’ve tried every which way of entering these but not sure which syntax magic will get me what I want here? Any ideas?

Thank you!

>Solution :

Try removing the braces around your styles.

 className={activeItem === tabItem ? styles.on : styles.off}

The first set of curly braces indicates jsx.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading