Home>

Can the component to be called be changed depending on the button clicked in React?

import Game1 from './Game1' // Create Game (1) component in a separate file
import Game2 from './Game2' // Create Game (2) component in a separate file
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render (
  <div>
    <div className = "intro">Select type of Game!</div>
    <button type = "button" className = "square_btn" name = "aaa" value = "aaa">to GAME1</button>
    <button type = "button" className = "square_btn" name = "bbb" value = "bbb">to GAME2</button>
  </div&gt ;,
  document.getElementById ('root')
  );

For example, as shown above, two buttons are prepared, and when button 1 is pressed, Game1 is called.
When button 2 is pressed, I want to call Game2 and display either one.
If either button is pressed, only the corresponding game is displayed on the screen (the button is also hidden).

I am sorry for this very rudimentary question, but I would appreciate it if you could tell me.

  • Answer # 1

    Let's make the entire "displayed part" into one component. Replacingrenderfrom outside depending on the situation can be a hassle.

    class Selector extends React.Component {
      state = {Component: null}
      selectGame1 = () =>this.setState ({Component: Game1})
      selectGame2 = () =>this.setState ({Component: Game2})
      render () {
        // If it does not start with a capital letter, JSX will not recognize it as a component
        const {Component} = this.state;
        if (Component) return<Component /> ;;
        return (
          <div>
            <div className = "intro">Select type of Game!</div>
            <button type = "button" className = "square_btn" name = "aaa" value = "aaa" onClick = {this.selectGame1}>to GAME1</button>
            <button type = "button" className = "square_btn" name = "bbb" value = "bbb" onClick = {this.selectGame2}>to GAME2</button>
          </div>
        );
      }
    }
    // Render<Selector />where used