0

Suppose I have a react component:

class myComponenet extends Component {
  state = {
    foo: "show",
  };

  hideit() {
    this.setState({
      foo: "hide",
    });
  }

  render() {
    return (
      <div
        className={this.state.foo}
        onClick={this.hideit}
      >
          <p>Some thing</p>
      </div>
    );
  }
}

How would I "bind" the class to foo, so that every time foo changes the component updates and rerenders, setting the classname equal to the new value of foo? Like vuejs does with v-bind:class="foo"

Peter Toth
  • 678
  • 6
  • 23
  • React doesn't have binding. The `this` value is likely being changed to `div` inside the click method. – evolutionxbox Feb 17 '21 at 01:43
  • 1
    Does this answer your question? [How does 'this' work in JavaScript?](https://stackoverflow.com/questions/1197822/how-does-this-work-in-javascript) – evolutionxbox Feb 17 '21 at 01:44
  • But then, how would I achieve the desired functionality? – Peter Toth Feb 17 '21 at 01:44
  • What you're doing is fine. Just follow the link I gave and it will tell you have to prevent the `this` from being changed in `hideit`. --- The simplist thing I can think of is changing `hideit() {` to `hideit = () => {` – evolutionxbox Feb 17 '21 at 01:46
  • 1
    @PéterSzabó-tóth, The comment by evolutionbox is correct and here is the example https://codesandbox.io/s/react-basic-class-component-forked-7f95w – Maniraj Murugan Feb 17 '21 at 02:07
  • 1
    try `className={{\`${this.state.foo}\`}}` if your className string is the same as `state.foo` – Eric Cheng Feb 17 '21 at 02:11
  • 1
    You can see more example on how to handle events in react here https://reactjs.org/docs/handling-events.html – Danny Ouellet Feb 17 '21 at 02:22

0 Answers0