2

I am trying to load a different React component using a button. It worked when doing it for authentication with GitHub using Firebase, but won't work for this page.

import React from 'react';
import './index.css';
import GamePage from '../Game';

class Home extends React.Component {
  constructor(props){
    super(props);
    this.LoadGamePage = this.LoadGamePage.bind(this);
  }
  LoadGamePage() {
    return(
      <div>
        <GamePage />
      </div>
    )
  }
  render(){
    return(
      <div className="home">
        <h1>Home Page</h1>
        <button onClick={this.LoadGamePage}>Play PIT</button>
      </div>
    )
  }
}

export default Home;

Is there something wrong with my LoadGamePage function?

D1TTO
  • 115
  • 8

1 Answers1

2

How it is supposed to work? You have an onclick handler, which calls a class method. That class method, called LoadGamePage, returns JSX. Okey, but what now? It is returned, but... not rendered. It won't display anywhere. What would I suggest you? Instead of returning the JSX inside that handler, I would set state and depending on state I would render the Game Page or not.

class Home extends React.Component {
  constructor(props){
    super(props);

    this.state = {
      gameVisible: false,
    }

    this.LoadGamePage = this.LoadGamePage.bind(this);
  }

  LoadGamePage() {
    this.setState({ gameVisible: true });
  }

  render() {
    if (this.state.gameVisible) {
       return <GamePage />
    }

    return (
      <div className="home">
        <h1>Home Page</h1>
        <button onClick={this.LoadGamePage}>Play PIT</button>
      </div>
    )
  }
}
kind user
  • 40,029
  • 7
  • 67
  • 77