Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 418
AnApprentice Avatar asked Jun 30 '17 04:06

AnApprentice


People also ask

How do you make an anchor tag with nothing?

To make an anchor tag refer to nothing, use “javascript: void(0)”. The following link does nothing because the expression "0" has no effect in JavaScript. Here the expression "0" is evaluated, but it is not loaded back into the current document.

Can we use onClick in anchor tag React?

To set an onClick listener on a link in React: Set the onClick prop on the link. The function you pass to the prop will get called every time the link is clicked.


1 Answers

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>       ...     ) 
like image 61
Ritesh Bansal Avatar answered Sep 28 '22 17:09

Ritesh Bansal