The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected.

Below is the code snippet I have implemented:

import react from 'react'

const account = () => {
    const [activeTab, tabActive] = react.useState("true")
    return (
        <>
            <div className='container my-5'>
                <ul className="nav nav-tabs">
                    <li className="nav-item">
                        <button type="button" className={"nav-link " + (activeTab?'active':'')} onClick={() => tabActive("true")}>Profile details</button>
                    </li>
                    <li className="nav-item">
                        <button type="button" className={"nav-link " + (activeTab?'':'active')}  onClick={() => tabActive("false")}>Select Colleges</button>
                    </li>
                </ul>
            </div>
            <div className='container my-5'>
                {
                    activeTab === "true" && <p>Value is true</p>
                }
                {
                    activeTab === "false" && <p>Value is false</p>
                }
            </div>
        </>
    )
}

export default account

Although the provided code seemingly fulfills the intended functionality, there seems to be an issue with toggling the active class between the two buttons effectively. Currently, both buttons have the class applied simultaneously or neither at all, rather than switching between them as expected.

Answer №1

Strings that are not empty will always be considered truthy. It's better to use booleans instead.

const account = () => {
  const [activeTab, tabActive] = react.useState(true);

  return (
    <>
      <div className='container my-5'>
        <ul className="nav nav-tabs">
          <li className="nav-item">
            <button
              type="button"
              className={"nav-link " + (activeTab ? 'active' : '')}
              onClick={() => tabActive(true)}
            >
              Profile details
            </button>
          </li>
          <li className="nav-item">
            <button
              type="button"
              className={"nav-link " + (activeTab ? '' : 'active')}
              onClick={() => tabActive(false)}
            >
              Select Colleges
            </button>
          </li>
        </ul>
      </div>
      <div className='container my-5'>
        {activeTab ? <p>The value is true</p> : <p>The value is false</p>}
      </div>
    </>
  )
};

Modification

If you have more than two tabs, consider using an index or a GUID to uniquely identify each tab and store this value in the state for the active tab. Then, check this value when rendering to match the active tab.

For example:

const account = () => {
  const [activeTab, tabActive] = react.useState(0);

  return (
    <>
      <div className='container my-5'>
        <ul className="nav nav-tabs">
          <li className="nav-item">
            <button
              type="button"
              className={"nav-link " + (activeTab === 0 && 'active')}
              onClick={() => tabActive(0)}
            >
              Profile details
            </button>
          </li>
          <li className="nav-item">
            <button
              type="button"
              className={"nav-link " + (activeTab === 1 && 'active')}
              onClick={() => tabActive(1)}
            >
              Select Colleges
            </button>
          </li>
          <li className="nav-item">
            <button
              type="button"
              className={"nav-link " + (activeTab === 2 && 'active')}
              onClick={() => tabActive(2)}
            >
              Select Something Else
            </button>
          </li>
        </ul>
      </div>
      <div className='container my-5'>
        {activeTab === 0 && <p>Current tab is 0</p>}
        {activeTab === 1 && <p>Current tab is 1</p>}
        {activeTab === 2 && <p>Current tab is 2</p>}
      </div>
    </>
  )
};

https://codesandbox.io/s/vigilant-payne-r7lvd4?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

Incorporate different courses tailored to the specific job role

https://i.stack.imgur.com/iGwxB.jpg I am interested in dynamically applying different classes to elements based on their position within a list. To elaborate: I have a list containing six elements, and the third element in this list is assigned the class ...

Issue: A React component went into suspension during the rendering process, however, no alternative UI was designated

I'm currently experimenting with the code found at https://github.com/adarshpastakia/ant-extensions/tree/master/modules/searchbar Although I followed the tutorial instructions, I encountered an error. Could it be that the library is malfunctioning? I ...

Next.js Error: Unable to access the 'collection' property, as it is undefined

I have recently started using next.js and I am interested in creating a Facebook clone by following YouTube tutorials. However, I keep encountering the error message "Cannot read properties of undefined (reading 'collection')". To troubleshoot, I ...

Managing POST request data in Express: A step-by-step guide

Currently, I am facing an issue with my alert button on the client side, which has an event listener that is supposed to send data to the server. Below is the code snippet for the client side: alertBtn.addEventListener("click", () => { axios ...

Retrieving all the information stored in the tables

I'm struggling with retrieving the content of my table cells. Some cells contain a hyphen (-) and if they do, I want to center the text. I'm facing difficulties with my jQuery code, particularly the if statement which always evaluates to false. ...

Restrict the duplication of div elements with JQuery

Here is the structure I'm working with: <div class="checkmark-outer"> <div class="checkmark-33"> <div class="fa-stack fa-1x checkmark-icon"> <i class="fa fa-circle fa-stack-2x icon-background"></i> ...

How can one transform a web-based application into a seamless full-screen desktop experience on a Mac?

"Which software can be utilized to enable a web application to display an icon on the desktop of a Mac computer, while also opening up the web application in a fully immersive full-screen mode that supports all the touch and gesture functionalities provi ...

Guide on sending a request to an API and displaying the retrieved information within the same Express application

I recently developed a basic express app with API and JWT authentication. I am now attempting to enhance the app by incorporating page rendering through my existing /api/.. routes. However, I am facing challenges in this process. app.use('/', en ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

The item is not functioning properly as intended

After delving into the concepts of prototype and proto, I believed that I had grasped the concept. However, something doesn't seem to add up. Can someone shed light on why directly accessing an Object like this does not yield the desired outcome? fun ...

A method for merging the values of three text fields and submitting them to a hidden text field

<label class="textRight label95 select205">Cost Center: </label> <input type="hidden" name="label_0" value="Cost Center" /> <input type="text" name="value_0" class="input64 inputTxtGray" value="" maxlength="10" /> <input type=" ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Develop a game timer using CreateJS

Looking for advice on the most effective method to create a timer clock using Createjs. I've attempted to reference HTML elements with DOMElement in the past, but encountered difficulties. Essentially, I need to display a timer within a container so p ...

Only class components can utilize ReactWrapper::state() in Unit Testing with Jest and Enzyme

Encountering an error while writing unit tests in React using Jest and Enzyme. The error message states: "ReactWrapper::state() can only be called on class components". import React from 'react'; import { mount } from 'enzyme'; import ...

Can someone explain the npm install messages from react-compare-app?

Scenario: I recently explored the react-compare-app example from React's examples page and decided to clone the repository. Following the usual procedure, I ran `npm install`. Initially, everything appeared normal as with most installations I have don ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Initiating an AJAX request to communicate with a Node.js server

Recently, I started exploring NodeJS and decided to utilize the npm spotcrime package for retrieving crime data based on user input location through an ajax call triggered by a button click. The npm documentation provides the following code snippet for usi ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

What could be causing the absence of several nodes in my three.js animations?

As I work on creating a portfolio using three.js, I've encountered an issue with my animation sets not playing after triggering an event. Initially, the code worked fine, but now I keep receiving a series of warnings and the code doesn't run at a ...