score:89
React events are actually Synthetic Events, not Native Events. As it is written here:
Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.
Try to use Use Event.stopImmediatePropagation
:
upvote: (e) ->
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
score:-2
You should pass the event object when you call the method. e.g
const handleOnSubmit = (e) => {
console.log("in submit");
e.preventDefault();
};
you should call this like
<form onSubmit={(e) => handleOnSubmit(e)}>
where you should pass e as the event object
score:0
If you use checkbox
<input
type='checkbox'
onChange={this.checkboxHandler}
/>
stopPropagation and stopImmediatePropagation won't be working.
Because you must using onClick={this.checkboxHandler}
score:0
If you are using React Router, I'd suggest looking into the react-router-bootstrap library which has a handy component LinkContainer. This component prevents default page reload so you don't have to deal with the event.
In your case it could look something like:
import { LinkContainer } from 'react-router-bootstrap';
<LinkContainer to={givePathHere}>
<span className="upvotes" onClick={this.upvote}>upvote</span>
</LinkContainer>
score:0
I've had some troubles with anchor tags and preventDefault
in the past and I always forget what I'm doing wrong, so here's what I figured out.
The problem I often have is that I try to access the component's attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault()
:
function (e, { href }) {
e.preventDefault();
// Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>
It seems the destructuring causes an error (Cannot read property 'href' of undefined
) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault
doesn't get called. If the href is #, the error is displayed properly since there's no actual reload.
I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:
function (e) {
e.preventDefault();
const { href } = e.target;
// Do something with href
}
...
<a href="/foobar" onClick={clickHndl}>Go to Foobar</a>
I hope this helps other people like me puzzled by not shown errors!
score:0
just like pure js do preventdefault : in class you should like this create a handler method :
handler(event) {
event.preventDefault();
console.log(event);
}
score:1
This is because those handlers do not preserve scope. From react documentation: react documentation
Check the "no autobinding" section. You should write the handler like: onClick = () => {}
score:1
I didn't find any of the mentioned options to be correct or work for me when I came to this page. They did give me ideas to test things out and I found that this worked for me.
dontGoToLink(e) {
e.preventDefault();
}
render() {
return (<a href="test.com" onClick={this.dontGoToLink} />});
}
score:2
The Gist I found and works for me:
const DummyLink = ({onClick, children, props}) => (
<a href="#" onClick={evt => {
evt.preventDefault();
onClick && onClick();
}} {...props}>
{children}
</a>
);
Credit for srph https://gist.github.com/srph/020b5c02dd489f30bfc59138b7c39b53
score:2
A nice and simple option that worked for me was:
<a href="javascript: false" onClick={this.handlerName}>Click Me</a>
score:8
render: ->
<a className="upvotes" onClick={(e) => {this.upvote(e); }}>upvote</a>
score:10
In a context like this
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
<a href="#" onClick={handleClick}>
Click me
</a>
);
}
As you can see, you have to call preventDefault() explicitly. I think that this docs, could be helpful.
score:16
try bind(this) so your code looks like below --
<a className="upvotes" onClick={this.upvote.bind(this)}>upvote</a>
or if you are writing in es6 react component in constructor you could do this
constructor(props){
super(props);
this.upvote = this.upvote.bind(this);
}
upvote(e){ // function upvote
e.preventDefault();
return false
}
score:86
A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();
upvotes = (e, arg1, arg2, arg3 ) => {
e.preventDefault();
//do something...
}
render(){
return (<a type="simpleQuery" onClick={ e => this.upvotes(e, arg1, arg2, arg3) }>
upvote
</a>);
{
Source: stackoverflow.com
Related Query
- React onClick and preventDefault() link refresh/redirect?
- React Router - Open Link on new Tab and Redirect to Home Page
- How to add redirect link to onclick Material ui icon - React
- Redirect and refresh page on form submission in React frontend
- React - How to detect Page Refresh and Redirect user
- React - Link redirect to item but not refresh the component
- Refresh token before Unauthorized Redirect in React and NodeJS
- How to save and pass username and password when redirect in external link in react
- Redirect to dashboard on refresh if user is logged in React and Typescript
- Page wont refresh when using React Link and passing state
- react button onClick redirect page
- How to use onClick event on react Link component?
- Get object data and target element from onClick event in react js
- React - how to capture only parent's onClick event and not children
- Netlify renders 404 on page refresh (using React and react-router)
- react link vs a tag and arrow function
- How to correctly redirect after catching authentication failure with Apollo and React
- React onClick and onTouchStart fired simultaneously
- React Routing Redirect onClick
- How to create a preview (Image and description) to the Url when shared link on Social media,Gmail and Skype using React JS?
- React JS : history.push is not a function error and it isn't navigating to a different page onclick of swal
- Handle React onDoubleClick and single onClick for same element
- React Link doesn't refresh the page
- React Router redirect hash link
- React js Redirect to main page when you try to refresh other pages
- Link react versions between linked library and workspace application
- React <a> tag and button onClick propagation
- Creating a Custom Button in React Typescript and add onClick Event
- How to create a link in React component with onClick handler?
- mapping an array of objects and changing the value with on onClick in React
More Query from same tag
- Modal pop-up not working properly (want the background page to dim)
- Comparison of Multiple Conditions Using Filters in React TypeScript
- Using AND operator inside JSX block of code
- Yup validation issue: Fields with their respective values present still says field is required
- React, styled-components, typescript errors
- fetchbyId in react wtih redux not working
- Taiwlwindcss: map through data elements with grid returns data in a single column
- Can't increasing the value in front end by react. Data comes from mongodb
- React image upload to FastAPI Unprocessable Entity
- How do I satisfy an "inexact function" error in Flow?
- How to Update script files in the browser immediately. when I updated scripts in the server
- How to get the ID of a new object from a mutation?
- How to add external JavaScript files in ReactJS
- Access yLabel for specific bar in chartJs without click
- When does React's setState change the state
- Modify React.js class -- override methods?
- Changing the state of one component that gets declared multiple times in React - Better Practices?
- In JSX how do I set a className as string + {prop}
- How to arrange graphics using CSS two by two in ReactJS
- How do I change the background color of the body?
- Reactjs, inline style with state data
- Display loading indicator until all the images in a gallery are (fully) loaded from an API in React (using Hooks)
- What classifies as a React functional component?
- onclick function in react-grid-layout to get checkbox checked
- Promise.all() problem using setTimeout(), state not updating
- Is there a way to use react router by viewing a single data from database using Laravel 8?
- how to install the new version of react app 5.0.0
- Test Coverage React, Istanbul -_registerComponent(...): Target container is not a DOM element
- Remove an item form an array in react
- state is not accessible inside a function in React