[reactjs] React onClick and preventDefault() link refresh/redirect?

I'm rendering a link with react:

render: ->
  `<a className="upvotes" onClick={this.upvote}>upvote</a>`

Then, above I have the upvote function:

upvote: ->
  // do stuff (ajax)

Before link I had span in that place but I need to switch to link and here's the trouble - every time I click on .upvotes the page gets refreshed, what I've tried so far:

event.preventDefault() - not working.

upvote: (e) ->
  e.preventDefault()
  // do stuff (ajax)

event.stopPropagation() - not working.

upvote: (e) ->
  e.stopPropagation()
  // do stuff (ajax)

return false - not working.

upvote: (e) ->
  // do stuff (ajax)
  return false

I've also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I'm doing wrong? I've checked event.type and it's click so I guess I should be able to avoid redirect somehow?

Excuse me, I'm a rookie when it comes to React.

Thank you!

This question is related to reactjs hyperlink coffeescript preventdefault

The answer is


render: -> <a className="upvotes" onClick={(e) => {this.upvote(e); }}>upvote</a>


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.


If you use checkbox

<input 
    type='checkbox'
    onChange={this.checkboxHandler}
/>

stopPropagation and stopImmediatePropagation won't be working.

Because you must using onClick={this.checkboxHandler}


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

A nice and simple option that worked for me was:

<a href="javascript: false" onClick={this.handlerName}>Click Me</a>

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


just like pure js do preventdefault : in class you should like this create a handler method :

handler(event) {
    event.preventDefault();
    console.log(event);
}

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

}

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 = () => {}


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!


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

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>

none of these methods worked for me, so I just solved this with CSS:

.upvotes:before {
   content:"";
   float: left;
   width: 100%;
   height: 100%;
   position: absolute;
   left: 0;
   top: 0;
}

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release Wrapping a react-router Link in an html button How to make a hyperlink in telegram without using bots? React onClick and preventDefault() link refresh/redirect? How to put a link on a button with bootstrap? How link to any local file with markdown syntax? link with target="_blank" does not open in new tab in Chrome How to create a link to another PHP page How to determine the current language of a wordpress page when using polylang? How to change link color (Bootstrap) How can I make a clickable link in an NSAttributedString?

Examples related to coffeescript

React onClick and preventDefault() link refresh/redirect? How to run Gulp tasks sequentially one after the other How do I get the Back Button to work with an AngularJS ui-router state machine? How does Trello access the user's clipboard? Create an ISO date object in javascript How to rotate a 3D object on axis three.js? Exec : display stdout "live" Ternary operation in CoffeeScript How to use executables from a package installed locally in node_modules? Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

Examples related to preventdefault

React onClick and preventDefault() link refresh/redirect? Bootstrap 3 - disable navbar collapse How to preventDefault on anchor tags? Stop form from submitting , Using Jquery Prevent Default on Form Submit jQuery What's the difference between event.stopPropagation and event.preventDefault? What is the opposite of evt.preventDefault(); How to unbind a listener that is calling event.preventDefault() (using jQuery)? event.preventDefault() function not working in IE