0

I have the following code - I would like to change the react component rendered on a button click. Clicking the button however does nothing. This is the parent class:

export default class SupportsContent extends React.Component {
  currentPage = "userSupportsList";
  goToPage = page => {
    this.currentPage = page;
  }
render() {
    let content = "";
    if (this.currentPage === "userSupportsList") {
      content = <UserSupportsList goToPage={this.goToPage} />
    } else if (this.currentPage === "chooseNewSupport") {
      content = <ChooseNewSupport goToPage={this.goToPage} />
    } else if (this.currentPage === "editSupport") {
      content = <EditSupport goToPage={this.goToPage} />
    } 
    return (
      <Grid>
        {content}
      </Grid>
    );
  }
}

I have the following child component definitions:

function UserSupportsList(props) {
  return (
    <ListItem button onClick={function () {props.goToPage("chooseNewSupport");}}></ListItem> 
  );
}
function ChooseNewSupport(props) {
  return (
    <p>Choose New Support</p>
    );
}

function EditSupport(props) {
  return (
    <p>Edit Support</p>
    );
}
2
  • goToPage() needs to be manually bound to .this i believe Commented May 21, 2019 at 4:05
  • 1
    Read about how to use state. You can't just set variables. Commented May 21, 2019 at 4:10

1 Answer 1

2

React updates a component based on two conditions: If either the components props change or the state is updated using the this.setState function.

I recommend you edit your component to use state instead of a variable:

class SupportsContent extends Component {
    state = {
        currentPage: "userSupportsList"
    }

    goToPage = page => this.setState({ currentPage: page })

    render() {
        let content = "";
        if (this.state.currentPage === "userSupportsList") {
            content = <UserSupportsList goToPage={this.goToPage} />
        } else if (this.state.currentPage === "chooseNewSupport") {
            content = <ChooseNewSupport goToPage={this.goToPage} />
        } else if (this.state.currentPage === "editSupport") {
            content = <EditSupport goToPage={this.goToPage} />
        } 
        return (
            <Grid>
                {content}
            </Grid>
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.