Search code examples
reactjsif-statementnext.jscss-modules

How can I create reusable function for this React code(active className)


I see that here you can come up with some kind of universal method for issuing an active class, but I just can’t figure out how to do it.

I would be very grateful for your help!

Logic

const engLangActive: string =
    router.locale === "en"
        ? `${styles.langButton} ${styles.active}`
        : styles.langButton;

const deLangActive: string =
    router.locale === "de"
        ? `${styles.langButton} ${styles.active}`
        : styles.langButton;

JSX

<>
  <button className={engLangActive}>
    EN
  </button>
  <button className={deLangActive}>
    DE
  </button>
</>

Solution

  • Since the code is exactly the same except for the language, you can loop over an array of language codes.

    const buttons = ['en', 'de', 'fr'].map(lang =>
        <button className={
            styles.langButton +
                router.locale === lang ? ` ${styles.active}` : ''
            }
            key={lang}
        >
            {lang.toUpperCase()}
        </button>
    );
    
    return <>{buttons}</>
    

    Don't forget the key attribute which is needed even in your own manual example for React to distinguish the button elements from each other.