How to toggle class on onclick in map function?

javascript toggle class onclick
jquery toggle between two classes
jquery toggle class onclick
javascript toggle button
jquery add remove class onclick
toggleclass is not a function
classlist.toggle not working
toggle class javascript vanilla

Toggling on a single element is a breeze. But I'm having a difficulty toggling with map function. Clicking a child element should toggle "active". But what's happening is that every element gets the class "active". Take a look:

constructor() {
   super()
   active: false

   this.toggleClick = this.toggleClick.bind(this)
}

toggleClick() {
   this.setState(state=> ({
         active: !state.active   
      })
   )
}

...in my function class...

function ThisClass(props){
   return(
      <div>
         {
            items.map((item,i) => {
               return(
                  <span role="button" className={`${props.active ? 'active' : ''}`} key={i} onClick={() => props.toggleClick(i)}>{item.text}</span>
               )
            })
         }
      </div>
   )
}

This is my desired output:

<div>
   <span class="active">A</span>
   <span class="">B</span>
   <span class="">C</span>
</div>

Instead, this becomes the result

<div>
   <span class="active">A</span>
   <span class="active">B</span>
   <span class="active">C</span>
</div>

And of course, toggling should be working. a single click would make the current active. And clicking it again would remove the active state. Also, By clicking the current state, the previous active element should be stripped off with active.

try assigning your "active" state an index instead of a boolean

change your code

from

className={${props.active ? 'active' : ''}}

to

className={${props.active === i ? 'active' : ''}}

Your toggle function must look like this

toggleClick(i) {
    this.setState({ active: i })
}

React js onclick toggle class in map function, Move the whole div and onClick handler to another component, and just map that component with props from the array. Something like: Learn how to select an HTML element by class and toggle its class in JavaScript. Suppose there’s a button that needs to show/hide a newsletter banner. Newsletter visibility is controlled by the CSS classes, adding Bootstrap 4 class d-none will hide a newsletter.

Here's my own solution(along with @404notBrighton): In my state: ...instead of

this.state = {active:false}

I've changed it to

this.state = {active:null}

in my toggleClick() I've put

this.setState({ active: i });
if (this.state.active === i) {
   this.setState({ active: null })
}

then finally in my class...

<span role="button" className={`${props.active === i ? 'active' : ''}`} key={i} onClick={() => props.toggleClick(i)}>

How To Toggle Between Class Names, Toggle between adding and removing a class name from an element with JavaScript. <button onclick="myFunction()">Try it</button> function myFunction() { Change the code to: navToggle = function { navNav.classList.toggle('active'); }; When you click #menu_button, this will refer to it, The class active should be added to #nav-toggle instead so that it'll animate

As I understand, you want to have only one active item.

You need to keep two state like selectedItemId and selectedItemState. And update their values when button is clicked.

So you can try something like this:

import React, { Component } from "react";

class App extends Component {
  state = {
    items: [{ id: 1, text: "A" }, { id: 2, text: "B" }, { id: 3, text: "C" }],
    selectedItemId: null,
    selectedItemState: false
  };

  toggleClick = id => {
    if (id === this.state.selectedItemId) {
      this.setState({
        selectedItemState: !this.state.selectedItemState
      });
    } else {
      this.setState({
        selectedItemId: id,
        selectedItemState: true
      });
    }
  };

  render() {
    const { selectedItemId, selectedItemState } = this.state;

    return this.state.items.map(el => (
      <div key={el.id}>
        <span
          role="button"
          className={
            el.id === selectedItemId && selectedItemState ? "active" : ""
          }
          onClick={() => this.toggleClick(el.id)}
        >
          {el.text} -{" "}
          {el.id === selectedItemId && selectedItemState ? "active" : "passive"}
        </span>
        <br />
      </div>
    ));
  }
}

export default App;

Sample codesandbox:

https://codesandbox.io/s/spring-thunder-w711z

jQuery toggleClass() Method, Toggle between adding and removing the "main" class name for all <p> elements : $("button").click(function(){ $("p").toggleClass("main"); });. Try it Yourself �� Toggle between adding a class name to the div element with id="myDIV" (in this example we use a button to toggle the class name).

.toggleClass(), A function that returns one or more space-separated classes or an array of classes to be toggled in the class attribute of each element in the matched set. Example: Call an Inline Function in an onClick Event Handler. An inline function is a function which is defined inside of the onClick handler when the React Component renders. It’s created on render because the function definition is inside of the onClick handler, which is inside of the component render method (or return, in the case of

.toggle(), A map of additional options to pass to the method. duration (default: 400 ). Type: Number or String. A string or number determining how long the animation� The toggleClass () method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.

jquery onclick toggle class next Code Example, This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This� Using onclick to create a dropdown button: // Get the button, and when the user clicks on it, execute myFunction document.getElementById("myBtn").onclick = function() {myFunction ()}; /* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */

Comments
  • Your answer works perfectly but not the one I was looking for. The purpose of toggle is when you click the same element again, it will negate itself of being active. Also, the other elements would negate themselves in active state after clicking the desired element.
  • No problem glad you found a solution
  • It helps but not the one I was looking for. I apologize but I have a missing statement. --- And of course, toggling should be working. a single click would make the current active. And clicking it again would remove the active state. Also, By clicking the current state, the previous active element should be stripped off with active.
  • @DaveMoreno ok I updated the answer, can you check again?
  • I appreciate your answer but I already have a solution, much shorter than your code. Anyways, perhaps you can still help me with my escalating issue regarding class toggle. Is it okay if I tag you on the next post?
  • @DaveMoreno please consider upvoting answers that helped you. Also there is no need to tag me :)