Home > Blockchain >  Change component when button is clicked reactjs
Change component when button is clicked reactjs

Time:09-27

I am trying to change the component after button is clicked. I have defined a changeComp() function in the class of my component and when the button is clicked I want to route it to the wallet-connect component but it doesnt seem to work. Kindly, help me out what am I missing here or why this practise is wrong?

changeComp(){
return (
            <Router>
                <Switch>
                    <Route exact path="/wallet-connect" component={WalletConnect} />
                </Switch>
            </Router>
        );}

<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => this.changeComp(event)} type="submit">Sign In</button>

CodePudding user response:

changeComp(){

const history = useHistory();

return (
            <Router>
                <Switch>
                    <Route exact path="/wallet-connect" component={WalletConnect} />
                </Switch>
            </Router>
<button className="btn w-100 mt-3 mt-sm-4" onClick={(event) => history.push("/wallet-connect")} type="button">Sign In</button>
        );}

CodePudding user response:

You can't return JSX from an event handler and expect it to be rendered into the DOM.

In your case you need to render the "/wallet-connect" Route into your main router and in the changeComp callback invoke an imperative navigation.

Main router:

<Switch>
  ...
  <Route path="/wallet-connect" component={WalletConnect} />
  ...
</Switch>

In component with button:

changeComp(event) {
  this.props.history.push("/wallet-connect");
}

<button
  className="btn w-100 mt-3 mt-sm-4"
  onClick={(event) => this.changeComp(event)}
  type="submit"
>
  Sign In
</button>

If the component doesn't have the route props injected then you'll need to decorate it with the withRouter Higher Order Component.

Suggestion:

Since the button is a type="submit" and if it's rendered within a form, then just issue the imperative navigation from the form's onSubmit handler.

submitHandler = event => {
  event.preventDefault();
  ...
  this.props.history.push("/wallet-connect");
}

...

<form onSubmit={this.submitHandler}>
  ...
  <button
    className="btn w-100 mt-3 mt-sm-4"
    type="submit"
  >
    Sign In
  </button>
</form>

If the button is not part of a form then specify the button type to be a "button" so it doesn't interfere with any form elements.

<button
  className="btn w-100 mt-3 mt-sm-4"
  onClick={(event) => this.changeComp(event)}
  type="button"
>
  Sign In
</button>
  • Related