Why isn't button changing from x to y in react?

114 Views Asked by At

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>
        );
    }
  }
3

There are 3 best solutions below

0
Nalhin On BEST ANSWER

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.

0
Bula On

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()

0
Andre On

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>
       );
   }
 }