MMalke
MMalke

Reputation: 2106

How to prevent an <a> tag from redirecting user, while keeping its href attribute?

I am working on a project in which we are using <button> elements as sort of links, as in, we open the page the user wants, difference being that we don't redirect user to the page, just render it in a div.

As we were discussing SEO strategies on another day, somebody mentioned how that was bad for our ranking in search engines, and how we should try using default <a> elements for that.

The only way I was able to achieve what I want is by setting the href="#" - which ruins the purpose of making the links crawable - and then calling event.preventDefault() on my <a>'s onClick handler.

I guess the question can be asked both ways:

How to prevent an <a> tag from redirecting user, while keeping its href attribute?

or

How can I make my links crawable while preventing them from redirecting the user, if clicked?

I have already tried:

And from this thread:

Upvotes: 0

Views: 1112

Answers (3)

codemonkey
codemonkey

Reputation: 7905

This will keep your href intact and prevent the page from redirecting there when clicked:

import React from "react";
import "./styles.css";

export default function App() {
  const [content, setContent] = React.useState(null);

  const handleClick = (e) => {
    e.preventDefault();
    setContent("New Content");
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <a href="somepage.html" onClick={handleClick}>
        click here
      </a>
      <hr />
      {content ? <div>{content}</div> : null}
    </div>
  );
}

Sandbox: https://codesandbox.io/s/practical-bush-mmpvo?file=/src/App.js

Upvotes: 1

Graeme Niedermayer
Graeme Niedermayer

Reputation: 124

Two ideas.

  1. If it is just for web crawlers you can use an invisible element using CSS. That way you could keep you original solution. Web crawlers often don't render CSS.

  2. You could put in an iframe. That way only the iframe will navigate.

Also if you have a robots.txt file web crawlers won't need to crawler though links.

Upvotes: 0

Ali Shoman
Ali Shoman

Reputation: 23

You can use React Router to render components, and it's contain a Link inside the library you can use it to keep the redirect inside your app without refreshing, so you can replace the with any .

Upvotes: 0

Related Questions