2

Is there any option to do something like this below?

toggle class to a specific element in reactjs

this is function

variable: any

onclick() {
  this.variable = 'new value';
}

<img src={ham} className="cursor-pointer" width="40" alt="" onClick={this.handleClick} />
<div className={this.variable + ' cursor-pointer'}>
  Content
</div>
Ponsakthi Anand
  • 305
  • 2
  • 13

1 Answers1

1

If you are wanting to toggle a className passed to an element then store a boolean state and conditionally add the classname. Toggle the state value in the click handler.

type MyState = {
  variable: boolean;
};

class Header extends Component<any, MyState> {

  state: MyState = {
    variable: false
  }

  handleClick = () => {
    this.setState(prevState => ({ variable: !prevState.variable }));
  }

  ...

  <img
    src={ham}
    className="cursor-pointer"
    width="40"
    alt=""
    onClick={this.handleClick}
  />
  <div className={this.state.variable ? 'cursor-pointer' : ''}>
    Content
  </div>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Hey Drew, Thank you for your quick response, but getting this error Property 'variable' does not exist on type 'Readonly<{}>'. TS2339 – Ponsakthi Anand Sep 28 '21 at 06:43
  • @PonsakthiAnand I'm not well versed in Typescript, but I do know this just means you need to define the interface/type for your component state that has whatever your state variables are used. I didn't use Typescript in my answer as it is, IMO irrelevant to the issue of toggling state and setting a classname. I'll update my answer to include an example though. – Drew Reese Sep 28 '21 at 06:44
  • https://ibb.co/rbFLx38 this is the code I have used. please check if you could help – Ponsakthi Anand Sep 28 '21 at 06:45