Search code examples
reactjsreact-nativerxjsreactjs-native

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


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

Solution

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