36

I have the following html element:

<a href onClick={() => fields.push()}>Add Email</a>

I need the href attribute so bootstrap styles the element with a link styling (color, cursor).

Problem is, if I click that now it causes the browser to redirect. How can I update the above to not redirect the browser onClick but still run fields.push()?

isherwood
  • 58,414
  • 16
  • 114
  • 157
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

17 Answers17

42

You should call preventDefault function from onClick event like this:

class App extends React.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <a href onClick={this.onClick} >Click me</a>
    )
  }
}

You can use something like this particular to your use case:

    const renderEmails = ({ fields }) => (
      ...
      <a href onClick={(e) => {
        e.preventDefault()
        fields.push()
      }}>Add Email</a>
      ...
    )
Ritesh Bansal
  • 3,108
  • 2
  • 16
  • 23
31

Here's a simple solution,

On React class component

class App extends React.Component {
  onClick() {
    console.log('onclick..')
  }

  render() {
    return (
      <a href={void(0)} onClick={this.onClick} >Click me</a>
    )
  }
}

React is dropping the javascript:void(0) solution and the href doesn't certainly accept the empty attribute value.

Basically what react wants us to do is to use a different component, for instance a button. We can always make a button look like a link using CSS(and thus, won't contain href and the complexity to remove it's behaviour). So, instead of using an anchor tag as a button, use the button element itself. Hope it makes sense.

Vectrobyte
  • 1,408
  • 12
  • 30
  • This is the cleanest solution which also supports selectively voiding via inline ternary. – Mat Lipe Feb 01 '20 at 16:16
  • Glad to help. :) – Vectrobyte Feb 01 '20 at 16:18
  • This doesn't work. The `href` attribute is simply dropped entirely during compilation. – Resigned June 2023 May 01 '20 at 00:50
  • @RadonRosborough Have you read the question above? The goal here is to make a link that does does nothing when clicked. With the above solution won't create any errors on the console and works as expected. But it's not a fail-safe solution. I have proposed an actual solution for that too using a button and transforming it to look like an anchor tag with CSS styling. – Vectrobyte May 04 '20 at 06:03
  • 3
    If I understand the question correctly, the goal is to create a link that does nothing **but still looks like a link**. If the `href` attribute is dropped, the link doesn't look like a link anymore. I will note that hacking a button to look like a link is [quite complicated](https://stackoverflow.com/q/1367409/3538165), and I wouldn't use it in production. – Resigned June 2023 May 04 '20 at 17:24
5

You should consider write method clickHappens in react component instead of writing this inline. Hope it works!

<a href onClick={(e) => {e.preventDefault(); fields.push()}}> Add Email </a>
patelarpan
  • 7,188
  • 2
  • 20
  • 25
Jan Ciołek
  • 1,796
  • 3
  • 17
  • 32
3

Add e.preventDefault() to onClick and add href="#" attribute

<a href="#" onClick={(e) => { e.preventDefault(); fields.push(); }}>Add Email</a>
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Oct 17 '20 at 11:08
1

Using Ritesh's answer, but without the issue of "Received true for a non-boolean attribute href", I simply swapped out the <a> tag with a <span>

class App extends React.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <span onClick={this.onClick}>Click me</span>
    )
  }
}
Shogo Yahagi
  • 141
  • 1
  • 2
0

Just make a custom component like this;

import React from "react";

export default function Link({ to, className, children }) {
  return (
    <a
      href={to}
      className={className}
      onClick={(e) => {
        e.preventDefault();
      }}
    >
      {children}
    </a>
  );
}
Soumen Khara
  • 128
  • 3
  • 5
0

Use a <button>

button {
  background: none!important;
  border: none;
  padding: 0!important;
  color: #069;
  text-decoration: underline;
  cursor: pointer;
}
<button type="button"> My link </button>
crg
  • 4,284
  • 2
  • 29
  • 57
0

try this code;

<a href={undefined} onClick={() => {/*function code*/}}></a>

void(0) returns undefined. so you should write directly undefined on React because javascript:URL deprecated by React.

https://reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-javascript-urls

G.Guvenal
  • 149
  • 7
  • 1
    While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please [include an explanation for your code](//meta.stackexchange.com/q/114762/269535), as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Luca Kiebel Jan 07 '22 at 12:20
  • @LucaKiebel Thanks for your information. I try to explain why. – G.Guvenal Mar 18 '22 at 22:06
0

This solution can also be helpful:

<a href={void(0)} onClick={(e)=>{
e.preventDefault();
}}>
angel.bonev
  • 2,154
  • 3
  • 20
  • 30
0

Here is a simple solution, it's worked for me:

   <a href={'/'} onClick={
                          (e) => {
                              e.preventDefault()
                              openProfileBox()
                          }
                      }
target="self" title='profile'>
{iconStyle(CgProfile)}
</a>

The "href" is a link for the index page, but with "e.preventDefault()" method, I can deny the link from work and call the second function to work successfully.

HasanRadi93
  • 17
  • 1
  • 2
0

I use it this way:

const url = '#'

<a href={url} onClick={() => alert('Test')}>Any text</a>
Leandro
  • 41
  • 2
0

I use this one liner to conditionally redirect, or not. Give null value to href, and it will be rendered as a dummy Anchor tag.

<a href={isDisableRedirect ? null : REDIRECT_LINK}>link</a>

// rendered as `<a>link</a>` in DOM.
zhuhang.jasper
  • 4,120
  • 4
  • 21
  • 29
-1
  1. no '#' in URL;
  2. no need to call e.preventDefault();
  3. simple~
 <a href={void(0)} onClick={()=>{console.log('...')}}>
simon
  • 1
  • 1
-1

Solution for Javascript:void(0); in React JS is to use the href="preventDefault()" . This will prevent the default behaviour of a link causing the page to refresh or navigate away.

Arahimx
  • 5
  • 1
  • 7
-3

add javscript:void(0):

<a href="javascript:void(0);" onClick={() => fields.push()}>Add Email</a>
Ashu
  • 1,320
  • 2
  • 10
  • 24
  • 11
    Thanks but that results in a js console message `50:21 warning Script URL is a form of eval no-script-url` – AnApprentice Jun 30 '17 at 04:18
  • 1
    This is the only solution here that works, but I get the warning `A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can` so presumably it will stop working soon. – Resigned June 2023 May 01 '20 at 00:51
-6

fields.push()}>Add Email

In TypeScript href="javascript:void(0);" throws warning, so there any other way to skip that warnings

-6

try the following code snippet

<a href="true" ....>