Home > Mobile >  How to use state as "active" indicator in React JS
How to use state as "active" indicator in React JS

Time:09-30

I have a state that shows which menu tab is currently active

const [activeTab, setActiveTab] = useState("home");

I use the state as class on my mark up

    <div className={`${activeTab}`}>
      <img src={Assets.Home} alt="Home" />
      <p>Home</p>
    </div>
    <div className={`${activeTab}`}>
      <img src={Assets.Wallet} alt="Wallet" />
      <p>Wallet</p>
    </div>

But that doesn't work since when the state changes it changes the class names of both divs. Now I want a way to use state as active indicator . I tried attaching an extra class for each div like this

        <div className={`home ${activeTab}`}>
          <img src={Assets.Home} alt="Home" />
          <p>Home</p>
        </div>
        <div className={`wallet ${activeTab}`>
          <img src={Assets.Wallet} alt="Wallet" />
          <p>Wallet</p>
        </div>

So that I can target in CSS. Like this

.home.home{
//some code
}

Whilst the above approach works it is messy. I would ideally like to just use the state as the class name without any extra addition. How can I do that?

CodePudding user response:

Use conditional rendering to check if the specific class is active and assign it a single class active in that case:

const [activeTab, setActiveTab] = useState("home");

<div className={`${activeTab === 'home' ? 'active' : ''}`}>
    <img src={Assets.Home} alt="Home" />
    <p>Home</p>
</div>
<div className={`${activeTab === 'wallet' ? 'active' : ''}`}>
    <img src={Assets.Wallet} alt="Wallet" />
    <p>Wallet</p>
</div>

You can then target the active class in CSS by defining:

.active {
    ...
}

CodePudding user response:

add the onClick handler at the tag to handle the activeTab state like <div onClick={() => setActiveTab("home")} className={${activeTab}}>{...}</div>

For your case you only need to do this:

<div onClick={() => setActiveTab("home")} className={`home ${activeTab}`}>
  <img src={Assets.Home} alt="Home" />
  <p>Home</p>
</div>
<div onClick={() => setActiveTab("wallet")} className={`wallet ${activeTab}`}>
  <img src={Assets.Wallet} alt="Wallet" />
  <p>Wallet</p>
</div>
  • Related