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

Time:09-29

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>

CodePudding user response:

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>
  • Related