Reputation: 6039
I have the following block inside my render()
(which is a Bootstrap Button: https://react-bootstrap.github.io/components.html#buttons-options):
<Button type="simpleQuery" onClick={this.handleEntailmentRequest.bind(this)}>
Query
</Button>
and the following function:
handleEntailmentRequest() {
console.log("handle request ");
}
Whenever I click on the button I can see that the "handle request" question appears in the console log, but suddenly disappears. My understanding is that something is causing the page to refresh. Any opinons where I am going wrong?
Upvotes: 35
Views: 106207
Reputation: 792
You can prevent the default behavior as suggested by zerkms or
Just add type="button" in button tag.
For example,
<button type="button" onClick={() => this.showSomething('all')}>All</button>
Upvotes: 22
Reputation: 1
We can use Link tag
</Link> instead of Anchor tag It will solve your Problem
Upvotes: 0
Reputation: 41
I don't know this helps at this point. but I added type="button" to the button I was using and my issue got solved. I don't think this would happen with other button elements. I used anchor tag and that is why I ran in to that issue. I used anchor tag in the following way and my problem went away.
<a type="button" onClick={}></a>
Upvotes: 2
Reputation: 11
You can also try this:
import React from 'react';
function App() {
function refreshPage() {
window.location.reload(false);
}
return (
<div>
<button onClick={refreshPage}>Click to reload!</button>
</div>
);
}
export default App;
Upvotes: 1
Reputation: 31
Yes! That did worked!
If your react-app gets refreshed unexpectedly then, you should pass (e) as an event argument and then use e.preventDefault()
in the function body which will prevent happen the default behavior of the onClick event.
Upvotes: 2
Reputation: 21873
The full solution for the issue of the page reloading will be:
<Button type="simpleQuery" onClick={(e) => {this.handleEntailmentRequest(e)}}>
Query
</Button>
handleEntailmentRequest(e){
e.preventDefault();
//do something...
}
Upvotes: 20
Reputation: 255155
The default button action is to submit the form.
If you don't need that - you need to prevent that:
handleEntailmentRequest(e) {
e.preventDefault();
console.log("handle request ");
}
References:
Upvotes: 54