Categories
React Answers

How to fix the anchor tag isn’t calling the onClick function issue in React?

Spread the love

Sometimes, we want to fix the anchor tag isn’t calling the onClick function issue in React.

In this article, we’ll look at how to fix the anchor tag isn’t calling the onClick function issue in React.

How to fix the anchor tag isn’t calling the onClick function issue in React?

To fix the anchor tag isn’t calling the onClick function issue in React, we can call e.preventDefault in our click event handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onClick = (e) => {
    e.preventDefault();
    console.log("clicked");
  };

  return (
    <a href="https:/example.com" onClick={onClick}>
      click me
    </a>
  );
}

to add the onClick function that calls e.preventDefault to stop the default behavior of going to the page with the URL set as the value of the href attribute.

And then we set the onClick prop of the a element to the onClick function.

As a result, we see 'clicked' logged in the console instead of going to https://example.com when we click on the link.

Conclusion

To fix the anchor tag isn’t calling the onClick function issue in React, we can call e.preventDefault in our click event handler function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *