简体   繁体   中英

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

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

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

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.

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>

e.preventDefault()添加到 onClick 并添加href="#"属性

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

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

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.

I use it this way:

const url = '#'

<a href={url} onClick={() => alert('Test')}>Any text</a>

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.

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.

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

添加 javscript:void(0):

<a href="javascript:void(0);" onClick={() => fields.push()}>Add Email</a>

fields.push()}>Add Email

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

试试下面的代码片段

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM