In this tutorial, you will learn some ways to disable a link in React js application.
How to Disable a Link in React JS
Here are 5 ways to disable link or anchor tag:
Method 1 – Using the disabled
attribute
Add a disabled attribute to the anchor () tag to prevent it from being clickable, like the following:
<a href="/some-link" disabled>Disabled Link</a>
Method 2 – Conditionally rendering the link
If you want to disable the link on the basis of any condition then you have to use condition statement for this, like the following:
{isDisabled ? null : <a href="/some-link">Clickable Link</a>}
Method 3 – Adding an event handler
You can also disable the link by using Event.preventDefault(), like the following:
function handleClick(event) { event.preventDefault(); } <a href="/some-link" onClick={handleClick}>Disabled Link</a>
Method 4 – Using CSS to style a disabled link
You can also disable links or anchors on simple HTML components using CSS, like the following:
const linkStyle = isDisabled ? { pointerEvents: 'none', color: 'gray' } : {};
return (
<a href="/some-link" style={linkStyle} onClick={handleClick}>
Styled Disabled Link
</a>
);
Method 5 – Wrapping the link in a button or custom component
Wrapping the link within a custom component (for example, a button) and controlling its behavior by enabling or disabling the component based on the logic of your application.
function CustomLink(props) {
return (
<button disabled={props.isDisabled}>
<a href={props.href}>Custom Link</a>
</button>
);
}
Conclusion
That’s it; you have learned 5 methods to disable link or anchor tags in react js.