0

I am trying to make a button that toggles between x and y. However, the following code isn't working. Why isn't this working? Sorry if it is an easy solution, I am new to react.

Right now, all that is appearing is a button that says X, and when I try to click it, nothing changes.

  constructor(props) {
    super(props);
    this.myValue = 2
  }

  buttonIsClicked() {
    this.myValue+=1
    this.render()
  }

  render() {
    switch(this.myValue%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }
helloworld12345
  • 176
  • 1
  • 4
  • 22
  • I believe the component does not render unless a state/props change is detected. `this.myValue` is neither of those. Try moving it such that it belongs to a state. And the `this.render()` doesn't actually force a render. – Bula May 29 '20 at 21:39
  • and it will be better if you toggle on the basis of true false with ternary operator. Just for improvement. – Shahanshah Alam May 30 '20 at 04:50

3 Answers3

1

In React, you cannot use object properties as a component state.

  constructor(props) {
    super(props);
    this.state = { counter: 0 };
  }

  buttonIsClicked() {
    this.setState({ counter: this.state.counter + 1 });
  }

  render() {
    switch(this.state.counter%2) {
      case 0:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
        );
      case 1:
        return(
        <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
        );
    }
  }

Also, you cannot call lifecycle methods directly (render for example).

If I were you, I'd start by reading React's documentation to avoid similar mistakes.

Nalhin
  • 392
  • 1
  • 6
  • 14
0

Check this as to why this.render() doesn't actually trigger a re-render. A better way to see this in action would be to move the variable to the state and then call this.setState()

Bula
  • 2,398
  • 5
  • 28
  • 54
0

React uses state to determine changes in its components. Check the official documentation to learn more about the lifecycle and state management: https://reactjs.org/docs/state-and-lifecycle.html

 constructor(props) {
   super(props);
   // init the state
   this.state = { myValue: 2 };
 }

 buttonIsClicked() {
   // accessing state
   const lastValue = this.state.myValue;
   // updating state which will trigger rendering
   this.setState({ myValue: lastValue + 1 });
 }

 render() {
   switch(this.state.myValue%2) {
     case 0:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>X</button>
       );
     case 1:
       return(
       <button className = "myButton" onClick={() => this.buttonIsClicked()}>Y</button>
       );
   }
 }
Andre
  • 4,185
  • 5
  • 22
  • 32