Andrew Schubert
Andrew Schubert

Reputation: 77

Render a component on a button click

I'm building a trivia game app with React-Redux and need to be able to render a TriviaCard component which starts a new game if a user decides to play again. Here is my button...

So, I have two buttons and need to be able to do something like this in my handleSubmit function...

<button onClick={this.handleSubmit} name="yes">Yes</button>
<button onClick={this.handleSubmit} name="no">No</button>

handleSubmit = (event) => {
    const answer = event.target.name
    if (answer === "yes") {
        return <TriviaCard />
    } else {
        //Do nothing...
    }
}

Upvotes: 2

Views: 7279

Answers (1)

margaretkru
margaretkru

Reputation: 2781

You can save the answer in the component's state and then use conditional render for TriviaCard component. Here is an example:

class Game extends React.Component {
    state = { answer: '' }
    handleSubmit = (event) => {
        this.setState({ answer: event.target.name });
    }
    render() {
      <div>
        {this.state.answer === "yes" && <TriviaCard />}
        <button onClick={this.handleSubmit} name="yes">Yes</button>
        <button onClick={this.handleSubmit} name="no">No</button>
      </div>
    }
}

When you click on one of the buttons, the state of the component will change triggering a rerender of the component. Then in render the state is used to determine whether to render TriviaCard or not based on the value of answer.

Upvotes: 8

Related Questions