skip to Main Content

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:

  • event.stopPropagation()
  • event.preventDefault()
  • return false;

And from this thread:

  • event.stopPropagation()
  • event.nativeEvent.stopImmediatePropagation()

3

Answers


  1. 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 .

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search