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
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 .
This will keep your href intact and prevent the page from redirecting there when clicked:
Sandbox: https://codesandbox.io/s/practical-bush-mmpvo?file=/src/App.js
Two ideas.
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.
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.