Home > Software design >  How can I create reusable function for this React code(active className)
How can I create reusable function for this React code(active className)

Time:09-22

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>
</>

CodePudding user response:

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.

CodePudding user response:

I would implement it this way:

const isLanguageActive = (languageCode) => {
    if (!languageCode) return '';

    return router.locale === languageCode
        ? `${styles.langButton} ${styles.active}`
        : styles.langButton;
}



<>
  <button className={isLanguageActive('en')}>
    EN
  </button>
  <button className={isLanguageActive('de')}>
    DE
  </button>
</>
  • Related