Ponsakthi Anand
Ponsakthi Anand

Reputation: 345

How to get or update the value in variables in reactjs like angular?

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>

Upvotes: 2

Views: 468

Answers (1)

Drew Reese
Drew Reese

Reputation: 203542

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>

Upvotes: 1

Related Questions