Search code examples
reactjsroutesonclickcomponents

i would like to open a component inside a component on click


moveToPreviousgames = () =>{ this.props.onRouteChange ('previousgames');}

render() {
    return (
            <div >
                 <Helmet>
                       <title> Match Fixtures</title>
                      <meta name='description' content='with this page users can see all the schedule games'/>
                      <meta name='keywords' content=' football, games,red lodge,Sports Pavilion,schedule,fixture,U11'/>
                   </Helmet>
            
                <Container  className="fixtureContainer">
                    <h1 className="fixtureTitle"> Match Fixtures </h1>

                    <button onClick={() => <Previousgames onRouteChange={this.props.onRouteChange} />}> Previousgames</button>
                       <p onClick={this.moveToPreviousgames}>Previousgames</p>

                </Container>  
                
                <Previousgames onRouteChange={this.props.onRouteChange} />
  
                <Sponsorbanner/>

            <Legalbanner onRouteChange={this.props.onRouteChange} />
            </div>
        );
    }
}

the line with button onclick just does not work. the line below with onclick just gives e a blank page but does not produce an error and the line Previousgames onRouteChange={this.props.onRouteChange} shows the component. what i want to achieve is show that component only after a click. taking me from one page to another. thx


Solution

  • If it's okay to load the <Previousgames/> and you don't need async loading, I'd say simply bind the render to a state change. Something like this should work:

    constructor() {
        super()
        this.state = {
            showGames: false
        }
    }
    
    render() {
        [...]
         <button onClick={() => { this.setState({ showGames: true }) }}>
            show games
         </button>
        {this.state.showGames && (
            <Previousgames onRouteChange={this.props.onRouteChange} />
        )}
    

    For async loading take a look how to work with React Suspense