0

Hi I am newbie in Reactjs.

I am trying to make each different toggle div classes when click buttons.

import React from 'react';

class Home extends React.Component{
  
  state = { isActive: false }; 
  handleToggle = () => {
    this.setState({ isActive: !this.state.isActive });
  }; 

  render(){  
    const isActive = this.state.isActive; 

    return (
      <>
        <button onClick={this.handleToggle} className={isActive ? "btn1" : "btn-on1"}>Toggle class1</button>
        <div className={isActive ? "box1" : "box-active1"}>11</div>
        <br />
        <button onClick={this.handleToggle} className={isActive ? "btn2" : "btn-on2"}>Toggle class2</button>
        <div className={isActive ? "box2" : "box-active2"}>22</div>
      </>
    )
  }
}
  
export default Home;

The problem is when click button, both button toggle together at same time. I want to make them each button toggle only itself.

How do I fix it ?

5
  • 1
    what do you mean "not working well."? Commented Apr 22, 2021 at 15:39
  • What is the issue that you are facing, what's not working well? Commented Apr 22, 2021 at 15:49
  • @Nithish I want to make them each button toggle only itself. Commented Apr 22, 2021 at 15:56
  • 1
    If you have multiple things that need their own state then each thing needs its own state; a single state value is insufficient. Commented Apr 22, 2021 at 16:01
  • Oh, you're just toggling between two? Commented Apr 22, 2021 at 16:08

1 Answer 1

2

I think you could achieve this by changing the state from boolean so it can refer to a specific div:

state = { isActive: '' }; 
  handleToggle = (btn) => {
    this.setState({ isActive: btn });
  }; 

  render(){  
    const isActive = this.state.isActive; 

    return (
      <>
        <button onClick={() => this.handleToggle('button1')} className={isActive === 'button1' ? "btn1" : "btn-on1"}>Toggle class1</button>
        <div className={isActive === 'button1' ? "box1" : "box-active1"}>11</div>
        <br />
        <button onClick={() => this.handleToggle('button2')} className={isActive === 'button2' ? "btn2" : "btn-on2"}>Toggle class2</button>
        <div className={isActive === 'button2' ? "box2" : "box-active2"}>22</div>
      </>
    )
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.