In React, how can I cause anchors to do nothing on click?

Viewed 47203

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()?

14 Answers

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.

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

<a href="#" onClick={(e) => { e.preventDefault(); fields.push(); }}>Add Email</a>

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

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

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>

This solution can also be helpful:

<a href={void(0)} onClick={(e)=>{
e.preventDefault();
}}>

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.

  1. no '#' in URL;
  2. no need to call e.preventDefault();
  3. simple~
 <a href={void(0)} onClick={()=>{console.log('...')}}>

fields.push()}>Add Email

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

try the following code snippet

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