Skip to content Skip to sidebar Skip to footer

In React, How Can I Cause Anchors To Do Nothing On Click?

I have the following html element: fields.push()}>Add Email I need the href attribute so bootstrap styles the element with a link styling

Solution 1:

You should call preventDefault function from onClick event like this:

classAppextendsReact.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <ahrefonClick={this.onClick} >Click me</a>
    )
  }
}

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

constrenderEmails = ({ fields }) => (
      ...
      <a href onClick={(e) => {
        e.preventDefault()
        fields.push()
      }}>AddEmail</a>
      ...
    )

Solution 2:

Here's a simple solution,

On React class component

classAppextendsReact.Component {
  onClick() {
    console.log('onclick..')
  }

  render() {
    return (
      <ahref={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.

Solution 3:

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

<ahrefonClick={(e) => {e.preventDefault(); fields.push()}}> Add Email </a>

Solution 4:

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

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

Solution 5:

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>

classAppextendsReact.Component {
  onClick = (e) => {
    e.preventDefault()
    console.log('onclick..')
  }
  render() {
    return (
      <spanonClick={this.onClick}>Click me</span>
    )
  }
}

Post a Comment for "In React, How Can I Cause Anchors To Do Nothing On Click?"