Categories
React Answers

How to cause anchors to do nothing on click in React?

Spread the love

Sometimes, we want to cause anchors to do nothing on click in React.

In this article, we’ll look at how to cause anchors to do nothing on click in React.

How to cause anchors to do nothing on click in React?

To cause anchors to do nothing on click in React, we can call e.preventDefault in the click handler function of the anchor.

For instance, we write:

import React from "react";

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

  return (
    <div>
      <a href="#" onClick={onClick}>
        Click me
      </a>
    </div>
  );
}

We have the onClick function that calls e.preventDefault to prevent the default action of going to the URL specified by the href attribute of the anchor.

Then we set the onClick prop of the anchor to the onClick function to use that as the click handler.

Now we should see 'on click' logged when we click on the anchor.

Conclusion

To cause anchors to do nothing on click in React, we can call e.preventDefault in the click handler function of the anchor.

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 *