Last updated on Aug 2, 2022 by Suraj Sharma
In this tutorial you will learn how you can disable a
link tags in React
We will use both CSS and Javascript ways to disable the link tag in React.
Suppose we have a simple <Home />
component with two a
element tags
import React from 'react';
const Home = ({disableHome})=>{
return (
<ul>
<li><a href="home">Home</a></li>
<li><a href=" dabout">About</a></li>
</ul>
);
}
export default Home;
set the css property pointer-events
to none
to disable the link using css
import React from 'react';
const Home = ({disableHome})=>{
return (
<ul>
<li>
<a href="home" style={disableHome ? {pointerEvents: 'none'}: {}}>
Home
</a>
</li>
<li><a href="about">About</a></li>
</ul>
);
}
And, the onClick
event handler of the link tag will call event.preventDefault()
method
import React from 'react';
const Home = ({disableHome})=>{
const handleLinkClick = (event) => {
event.preventDefault()
}
return (
<ul>
<li>
<a
href="home"
style={disableHome ? {pointerEvents: 'none'}: {}}
onClick={handleLinkClick}
>
Home
</a>
</li>
<li><a href="about">About</a></li>
</ul>
);
}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.