sortof
sortof

Reputation: 541

How to change only the class i pressed on

I am trying to change class onClick event for a single element, right now my code is changing to all the elements.

how do i change the class only for the element i pressed on (there is a lot of Colxx elements, by a loop that draw them, this is example of 1 of them )

i try this:

I am trying to change class onClick event for a single element, right now my code is changing to all the elements.

how do i change the class only for the element i pressed on (there is a lot of Colxx elements, by a loop that draw them, this is example of 1 of them )

i try this:

constructor(props) {
    super(props);
    this.state = {
        active: false
    };
    this.toggleClass= this.toggleClass.bind(this);
}

toggleClass() {
    const currentState = this.state.active;
    this.setState({ active: !currentState });
};




<Colxx 
    xxs="4" lg="4" xl="4" mb="4" md="4"
    className={this.state.active ? 'whowillwinselected': 'teamhover'}
    onClick={this.toggleClass}
>
</Colxx>



.teamhover:hover {
    cursor: pointer;
    background-color:rgba(0, 0, 0, 0.5);

}

.whowillwinselected {
    background-color:green;
}

Upvotes: 0

Views: 68

Answers (2)

Neetigya Chahar
Neetigya Chahar

Reputation: 693

Define your state as:

this.state = {
    active: null
};

toggleClass() as:

const toggleClass = event => {
   const value = (event.target.key === this.state.active) ? null : event.target.key;
   this.setState({ active: value});
}

And get a unique key from the loop and provide it to <Colxx .../>. Then update the match condition.

<Colxx 
          xxs="4" lg="4" xl="4" mb="4" md="4"
          key={key}
          className={(this.state.active === key) ? 'whowillwinselected': 'teamhover'}
          onClick={this.toggleClass}
          >

So when a particular <Colxx .../> is clicked, its key is updated to state. Then the match condition works accordingly.

  • I have set value = null when event.target.key === this.state.active so as to remove the class if its already toggled on.

Upvotes: 1

Pranav
Pranav

Reputation: 98

You could implement <Colxx .../> as a separate functional component with react, so that it has it's own local state and onClick function independent of everything else.
Example functional Component:

import React, {useState} from 'react';
//Other necessary imports


function MyCol(props){
  const[active,setActive]=useState(false);
  return(
    <Colxx /*options*/ 
        className={active ? 'whowillwinselected': 'teamhover'}
        onClick={()=>{setActive(!active);}}
   />);
}
export default MyCol

Import this in your your file where it's needed and use it like a normal component.

import MyCol from 'pathtofile'
/*code*/
<MyCol />
/*code*/

This makes use of react hooks in order to manage state.

Upvotes: 1

Related Questions