Switching component upon button click in ReactJS

After clicking the button, I want to change the component displayed on the screen. I have created a function called changeComp() within my component's class. However, when I click the button, it doesn't route to the wallet-connect component as expected. Can someone please assist me in understanding what I am doing wrong here or why this approach might be incorrect?

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>

Answer №1

Avoid trying to return JSX from an event handler and expecting it to be displayed in the DOM.

In this scenario, make sure to include the "/wallet-connect" Route within your main router and use imperative navigation in the changeComp callback.

Main router:

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

In the component with the 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 does not receive the route props, you may need to enhance it with the withRouter Higher Order Component.

Suggestion:

When using a button with type="submit" inside a form, handle the imperative navigation in the form's onSubmit function.

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, specify its type as "button" to prevent interference with any form elements.

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

Answer №2

modifyComp(){

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>
        );}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Internet Explorer versions 7 and 8, a transparent overlay div enables click-through functionality

I am facing an issue with a div containing form elements and an invisible overlay mask. When using IE 7 and 8, the click goes through the overlay without background which is incorrect. To solve this problem, I added a background color to the overlay div w ...

Animate your menu on hover with jQuery!

I am experiencing an issue with centering the background image below a link. When using mouseleave, the image does not return exactly to the center of the list. Any assistance on how to resolve this would be greatly appreciated. Thank you! Here is the ref ...

Excessive CPU usage caused by a patch in jQuery dealing with regular expressions

Working on a project developed by an unknown individual has presented some challenges. Without any means of contact with this person, I noticed that the browser's CPU consumption spikes significantly upon loading the page. Upon further investigation, ...

Playing with JSON data in React

I am currently working on developing my React UI to be dependent on a JSON file. Despite reading numerous articles, I have yet to find a solution that is both understandable and applicable to my project. The closest resource I found is about loading json d ...

Using jQuery to create a Select All Checkbox that toggles a specific class

I have come across similar examples in the past, but I have been unable to make it work as intended. The examples I found only use standard checkboxes. I attempted to customize the checkbox using a sprite sheet by applying a class, but I am struggling to a ...

Aligning a element at the center is not functioning properly when using margin: 0 auto;

I'm having trouble aligning elements to the center when applying margin: 0 auto. You can view the code here: https://jsfiddle.net/helloworld123/vhhx1o7n/ The goal is to align the elements in the center of the page (.entry-wrap should be centered) and ...

Automatic keyboard suggestions not working for HTML search input using Ajax

I am currently working on a PHP web application that uses a MySql database. I have implemented a search suggestion box using ajax. The issue I am facing is that the suggestions can be selected with the mouse and auto-completed, but not when using the keybo ...

Sometimes the AngularJS scope is refreshed only intermittently

I am encountering an issue with a list of cards retrieved from an API and displayed in a table using ng-repeat. The problem arises when I attempt to delete a card - sometimes it remains in the view, while other times it disappears as expected after confirm ...

What could be causing next/image to fail in resizing images post-release only on a local server?

We've encountered a strange issue with image optimization and we're curious if anyone else has experienced something similar. Within our code base, we have implemented the following code for rendering images: imageElements: screenshotImageUrls?. ...

Exploring the capabilities of JSON.stringify in Internet Explorer 11

I encountered a puzzling issue with my JavaScript code – it works flawlessly in Google Chrome 49.0.2623, but causes my entire file to crash in Explorer 11. The problem arises when I attempt to 'Export' JavaScript objects using AJAX. Let me shar ...

What is the process for updating my handle and sending it to the reducer function?

It's been a challenge trying to convert my authentication form submission to a reducer over the past three days. I've scoured every resource available but only found a partial solution for handling change. However, I'm stuck on implementing ...

What is the best way to display two items side by side from a list of items in HTML?

I have a list of items that are displayed in `webView` with 4 elements per row. However, for `mobileView`, I would like to show only 2 elements in each row. Below is an example from my HTML file: <div class="row my-3 cust-heading" style="margin-left: 3 ...

Navigation Menu Spanning Across Full Width of All Screens

Hello! I am currently working on designing a responsive menu using HTML5 and CSS. My approach involves creating a navigation menu for desktop computers and implementing a checkbox with a label to reveal the responsive menu when needed. Here is the code s ...

What is the best way to eliminate empty space at the bottom of a page that is being caused by a button?

I have identified the reason for the blank space at the bottom of my page - it's due to a sticky "back to top" button. However, I am unsure how to resolve this issue. Here is the layout of the page: <nav> navbar </nav> <div> car ...

What location is most ideal for incorporating JavaScript/Ajax within a document?

Sorry for the seemingly simple question, but I would appreciate some clarification from the experts. When it comes to the three options of placing JavaScript - head, $(document).ready, or body, which would be the optimal location for ajax that heavily rel ...

What is the best way to insert data from a promise into MongoDB?

While attempting to integrate an array of JSON data from a different server into a MongoDB collection, I encountered the following error message: "Cannot create property '_id' on string". Even though I am passing in an array, it seems to be causi ...

What is the best way to achieve a column layout using Bootstrap?

I'm having difficulty adjusting the column width in Bootstrap columns to my specific needs. Check out this link for more information: : https://i.sstatic.net/Tvdef.png What I'm trying to achieve is to keep the label column width fixed while all ...

Transitioning smoothly between different backgrounds will be like changing the cursor color

As I work on my website, I encounter the need for a cursor that smoothly changes its color. Specifically, I want the cursor to appear blue (#0059ff) when hovering over a white background and white when over a blue background, with a seamless transition lik ...

The has-error class cannot be applied to certain input elements

I am currently in the process of validating some inputs within a modal: <div id="modal-section" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="m ...

encountered issue accessing optional property post validation check

flow 0.67.1 (although behavior still present in version 0.73.1) For Instance: type PropOptional = { prop?: ComplexType }; type ComplexType = { callable: () => void, anotherCallable: () => void }; function usePropOpt ...