Search code examples
javascripttwitter-bootstrapreactjsbootstrap-4

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


Solution

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