Activating a div in React.js using setActive: Step-by-step guide

Currently, I am in the process of developing an application with three menu tabs, each represented by an accordion comprising a menu title and content. The issue I am facing is that when clicking on any menu title, all content divs are displayed simultaneously. My goal is to have each menu title trigger only the content div associated with it, activating the active state exclusively for that specific div.

The toggle accordion function I have formulated opens all content windows simultaneously. Upon clicking any menu title, all corresponding content is revealed. Below is a simplified version of my function:

function PlayerApp(props) {

  const [setActive, setActiveState] = useState("");
  const [setHeight, setHeightState] = useState("0px");

  const content = useRef(null);

  function toggleAccordion() { 

    setActiveState(setActive === "" ? "active" : "");

    setHeightState(
      setActive === "active" ? "0px" : `${content.current.scrollHeight}px`
    );
  }

  return (

  <div className="content"> 

    <div className="content-list">
      
       <div ref={content} style={{ maxHeight: `${setHeight}` }} className="accordion__content">
       <div className="accordion__text"> text content here </div>

       </div>
      </div>

      <div className="content-list">
        
        <div ref={content} style={{ maxHeight: `${setHeight}` }} className="accordion__content">
        <div className="accordion__text"> text here </div>

       </div>
      </div>

      <div className="content-list">

        <div ref={content} style={{ maxHeight: `${setHeight}` }} className="accordion__content">
        <div className="accordion__text"> text content here </div>

       </div>

      </div>

        <div className="content-title">
          <button className={`menu_title1 ${setActive}`} onClick={toggleAccordion}>
            <p className="accordion__title">Menu 1:</p>
            </button>
        </div>

          <div className="content-title">
          <button className={`menu_title2 ${setActive}`} onClick={toggleAccordion}>
            <p className="accordion__title">Menu 2:</p>
            </button>
        </div>
           <div className="content-title">
          <button className={`menu_title3 ${setActive}`} onClick={toggleAccordion}>
            <p className="accordion__title">Menu 3:</p>
            </button>
        </div>

        </div>

  );
}

export default PlayerApp;

Although I have designated unique classes for each button, they still all trigger the active state for every div upon clicking. I am seeking guidance on how to modify my function to ensure that each button causes a distinct response for its associated accordion window.

How can I adjust my function so that clicking on each button results in a unique response specific to that accordion window?

Answer №1

One efficient way to enhance the organization of your code is to utilize an array for storing menu details.

const menuItems = [
    { id: 'menu1', text: 'Menu 1' },
    { id: 'menu2', text: 'Menu 2' },
    { id: 'menu3', text: 'Menu 3' },
  ];
  const [activeMenuItem, setActiveMenuItem] = useState();

The corresponding HTML structure would then look like this:

{menuItems.map((item, index) => {
          return (
            <div className="menu-item">
              <button
                className={`menu ${activeMenuItem === item.id ? 'active' : ''}`}
                onClick={() => {
                  setActiveMenuItem(item.id);
                }}
              >
                <p className="menu__text">{item.text}</p>
              </button>
            </div>
          );
        })}

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

The Transform feature doesn't seem to be functioning as expected within the Bootstrap

I was experimenting with creating a simple transform transition animation using css and js, so I wrote the following code: (test page) <!DOCTYPE html> <html> <head> <style type="text/css"> *{ ...

Mapbox is capable of managing several GEOJSON files by utilizing the loadURL function

I am in the process of creating a map that is designed to load multiple layers from various sources based on a configuration file called config.json. Each layer should trigger a popup when clicked, but oddly enough, I am only able to see the popup for the ...

When attempting to showcase an MUI icon that was imported, I encounter the following issues: Invalid hook call and the <ForwardRef(SvgIcon)> component

Encountering issues while trying to display an imported MUI icon leads to the following errors: Error: https://i.stack.imgur.com/USdEx.png Sample Code: import React from 'react' import ThreeDRotation from '@mui/icons-material/ThreeDRotati ...

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

Error: JavaScript encountered an unterminated string literal issue

Whenever I try to add the following two lines in the section of my application's homepage, my browser throws a JavaScript error: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window. ...

Customize the appearance of alert boxes in ajax requests

Is there a way to customize the default ajax alert box? I currently have code that deletes a user and reloads the current page. It functions properly, but I want to enhance the styling of the alert box that appears before the user is deleted. function d ...

Restoring the dropdown list in a React Material-UI Autocomplete widget

We are currently designing an autocomplete feature using Material UI for our React application. Our objective is to dynamically generate the dropdown list as part of a search function, which is functioning correctly. However, we are facing an issue where t ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

Can you use CSS to target a parent div based on the elements it contains?

If I have the following HTML: <div class='row'> <div class='cell'> <span class='image'> </span> Image Cell </div> <div class='cell'> Regular Cell </div&g ...

"Stellar.js fails to function properly when applied to elements loaded dynamically through AJAX requests

I recently implemented the amazing Stellar.js for parallax effects in a project of mine. However, I've encountered an issue: Stellar.js does not recognize when I update content via AJAX (specifically loading new div elements from an HTML file and rep ...

Issue encountered while attempting to utilize the concat method to condense an array

Describing the Problem: I am facing a challenge with flattening an array of sales data. Each element in the array contains an ID, sale code, seller username, timestamp, and details which include an array of products, quantities, and subtotals for each item ...

Challenges encountered while developing Angular FormArrays: Managing value changes, applying validators, and resolving checkbox deselection

I am facing an issue with my Angular formArray of checkboxes. In order to ensure that at least one checkbox is selected, I have implemented a validator. However, there are two problems that I need to address: Firstly, when the last checkbox is selecte ...

How to display only the even numbers in a numeric array with ReactJs

I am currently facing a challenge with extracting even numbers from a numeric array in ReactJs. While it is a simple task in languages like Python, I seem to be struggling with implementing the logic correctly in my React code. Here's what I have so f ...

I've exhausted all my knowledge but still unable to get Tailwind to work

I've been troubleshooting Tailwind for the past 6 hours. Managed to set it up in a simpler Nextjs/React/Typescript project, but struggling to get it working in this larger codebase. I'm sure I'm missing something obvious, but I'm at a ...

Express.js throwing an unexpected 404 error

I'm really struggling to understand why Node (express) only renders the index page and returns a 404 error for other pages, like "comproAffitto" in this example. In my app.js file: var index = require('./routes/index'); var comproAffitto= ...

Pop-up message on card selection using JavaScript, CSS, and PHP

I have a total of 6 cards displayed in my HTML. Each card, when clicked, should trigger a modal window to pop up (with additional information corresponding to that specific card). After spending a day searching for a solution online, I've come here s ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

Blank space appearing at the bottom of webpage

I have a strange issue with my document where there is a small white gap at the end. Upon inspecting the element, it seems to be related to the body. Any suggestions on how to resolve this? ...

Prevent the resizing of my website on iOS devices using HTML and CSS

I'm encountering an issue with a website I developed that seems to be resizable on certain iOS devices, including the new iPhone X. I haven't been able to replicate this behavior on other standard websites. Perhaps there's a simple CSS solut ...

Having trouble uploading a file using the React frontend

I am currently facing an issue with uploading images from React Frontend to Cloudinary. I have created a backend API called upload image. When I test it through Postman, the files are successfully uploaded to the Cloudinary Server. However, when I try to u ...