I am searching for a way to apply a conditional class to the chosen element in react, as the toggle method does not

I'm working on customizing a dropdown menu and I want to add a functionality where if a parent li menu has an arrow class before the ul element, then clicking on that parent li menu will add a class called showMenu only to that specific sub-menu.

Here is the code snippet:

<ul className="nav-links">
    <li>
        <a href="#">
            <i className='bx bx-grid-alt'></i>
            <span className="link_name">Dashboard</span>
        </a>
        <ul className="sub-menu blank">
            <li><a className="link_name" href="#">Category</a></li>
        </ul>
    </li>
    <li onClick={subMenuToggle} className={`${subMenu ? 'showMenu' : ''}`}> // sub menu parent
        <div className="iocn-link">
            <a href="#">
                <i className='bx bx-collection'></i>
                <span className="link_name">Category</span>
            </a>
            <i className='bx bxs-chevron-down arrow'></i> // arrow class
        </div>
        <ul className="sub-menu">
            <li><a className="link_name" href="#">Category</a></li>
            <li><a href="#">HTML & CSS</a></li>
            <li><a href="#">JavaScript</a></li>
            <li><a href="#">PHP & MySQL</a></li>
        </ul>
    </li>
    <li onClick={subMenuToggle} className={`${subMenu ? 'showMenu' : ''}`}>// sub menu parent
        <div className="iocn-link">
            <a href="#">
                <i className='bx bx-book-alt'></i>
                <span className="link_name">Posts</span>
            </a>
            <i className='bx bxs-chevron-down arrow'></i> // arrow class
        </div>
        <ul className="sub-menu">
            <li><a className="link_name" href="#">Posts</a></li>
            <li><a href="#">Web Design</a></li>
            <li><a href="#">Login Form</a></li>
            <li><a href="#">Card Design</a></li>
        </ul>
    </li>
</ul>

I have attempted to implement this functionality by setting an onClick handler subMenuToggle in the parent submenu li. However, when I click on any sub menu parent item, it opens all the sub-menus instead of just the one I clicked on.

 const [subMenu, setSubMenu] = useState(false)
    const subMenuToggle = () => {
        setSubMenu(!subMenu)
    }

Any help would be greatly appreciated!

Answer №1

It seems like there may be a simpler way to achieve the desired functionality. Instead of using a separate subMenu state, you can utilize the classList property of the element that is being clicked on.

const subMenuToggle = (e)=>{
  e.currentTarget.classList.toggle('showMenu');
}

Incorporate this approach by updating your li elements as follows:

/* In addition to 'showMenu', you can add any default classes required for this element */
<li onClick={subMenuToggle} className=""> // parent menu item
   <div className="iocn-link">
      <a href="#">
        <i className='bx bx-collection'></i>
          <span className="link_name">Category</span>
      </a>
      <i className='bx bxs-chevron-down arrow'></i> // arrow icon
   </div>
   <ul className="sub-menu">
     <li><a className="link_name" href="#">Category</a></li>
     <li><a href="#">HTML & CSS</a></li>
     <li><a href="#">JavaScript</a></li>
     <li><a href="#">PHP & MySQL</a></li>
   </ul>
</li>

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

Guide on setting a v-model within a v-for loop (using an example from Bootstrap Vue)

Currently, I am utilizing vue-bootstrap for creating input fields using a v-for directive. The objective is quite similar to the example provided in this link. However, I am encountering some difficulties in obtaining the data collected from these inputs i ...

Accelerate blinking timer by utilizing CSS3 animations

I'm currently developing a quiz application that includes a timer counting down from 10 seconds to 0 seconds. As the timer reaches closer to 0 seconds, I am looking to implement a feature where my text blinks faster and faster. Additionally, I would l ...

Repetitive calling of a Node.js function

Currently, I am developing using the nodejs express framework. On my webpage, there are two buttons: 1) Submit, which triggers the following function: router.get('/record_enrich_quick/:quick', function(req, res) { console.trace(); var j ...

Implement the TypeScript handleChange function for input fields and dropdown menus

Currently, I am in the process of developing a form using TypeScript and Material-UI components. My objective is to create a change handler function that can be utilized for both select and textfield changes. Below are my state and functions: const [re ...

Working with JavaScript Arrays within a JSON file data

I am currently learning React and attempting to display random images from the Picsum website using their API. The JSON file I receive contains various information, but I am specifically interested in extracting the image URLs. Although it appears that my ...

"Utilizing ng-select with ng-model: A Step-by-Step Guide

Currently, I am working on a code that involves using ng-repeat to loop through options. My goal is to utilize ng-select to choose a value based on a specific condition. However, according to the AngularJS documentation: ngSelected does not interact wit ...

Error: Uncaught TypeError - Unable to access the 'handleClick' property of undefined within a forEach loop

I came across the following code snippet articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { constructor(props) { super(props); this.state ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

vue-router: A guide to disabling the outline property of the CSS in router-link

I am having trouble disabling the outline of a css link element. I successfully disabled the outline of a regular link using a css class, but I am unable to do so with the <router-link> element. How can I disable the outline for this? .page-link, .p ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Node.js Express refuses to serve .js files with absolute URLs

I have encountered a perplexing issue with two files located in /public/widget, namely help.html and help.js http://localhost:8084/widget/help.html When entered into the address bar, it functions normally However, when attempting to access http://local ...

Are there any techniques for running unit tests on a Vue.js transition?

I have been working on a Vue component that includes a transition with a dynamically generated name. My challenge is to test whether the transition name is correctly set based on the props I pass into the component. Below is the code snippet of the compone ...

Is it possible for me to adjust the size of the Facebook login button on my website?

I have implemented a Facebook login on my website using the following code: <fb:login-button scope="public_profile,email" onlogin="checkLoginState();"> </fb:login-button> Is it possible to replace this button with a standard button or adjust ...

problems with the way white space is displayed on the right side of the page in Opera and Safari

Hello, I am having an issue where Opera and Safari are displaying extra white space on the right when I use percentages for my width. Below is my code snippet: Safari 5.1 and Opera 11.11 View sample fiddle here HTML: <!DOCTYPE html PUBLIC "-//W3C//D ...

What is the reason for this MongoDB document consistently having the identical nanoid?

Although I've managed to find a solution, my main concern is understanding the root cause of the bug. In the scenarios below, MongoDB documents are being created with identical id and date values respectively. id: { type: String, required: tru ...

Exploring sagas: Faking a response using a call effect

In my current scenario, I am facing a challenging situation: export function* getPosts() { try { const response = yield call(apiCall); yield put({ type: "API_CALL_SUCCESS", response }); } catch(e) { // ... } Furthermore, there is a spec ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Is there a way to eliminate the border of an image attribute pulled from an input field?

Seeking assistance with a persistent issue I'm facing. I have an input for an image and a script to display the selected image. However, when the input is empty, a frustrating black border appears around the image attribute. How can I remove this bord ...

Guide on setting up an API route in Next.js to efficiently transmit a CSV file to the frontend

From what I understand (please correct me if I'm mistaken), the usual process for downloading a file involves the frontend making a call to an API route, with most of the operations occurring on the server side. My current task involves reading data ...