How to disable a Link in React
There are three ways to disable a link in React.
- Set pointerEvents curser property into none
- Use event.preventDefault() in onClick event handler
- Conditionally rendering the Link component
Set pointerEvents curser property into none
The CSS property pointer-events
defines whether an element reacts to pointer events or not. If it is set to none
, the associated element (button, link, etc) will do nothing on click and the link will be disabled.
Let us take an example of the below code.
import {useState} from 'react';
import {BrowserRouter as Router, Link} from 'react-router-dom';
function App() {
const [clickable, setClickable] = useState(true);
return (
<Router>
<div>
<Link style={{pointerEvents: clickable ? '' : 'none'}} to="/">
Home
</Link>
<button onClick={() => setClickable(!clickable)}>Toggle</button>
</div>
</Router>
);
}
export default App;
In this example, when a user clicks on the button, clickable
the state got toggled. The pointer-events property of the Link is set to none
with the help of the ternary operator clickable ? '' : 'none'
and the link will be disabled.
This can also be used for anchor tag elements because, <Link>
is really an <a>
tag under the hood.
Use event.preventDefault() in onClick event handler
We can use event.preventDefault() in onClick event handler to disable a link in React.
import {BrowserRouter as Router, Link} from 'react-router-dom';
function App() {
const ClickHandler = (event) => {
event.preventDefault();
};
return (
<Router>
<div>
<Link onClick={ClickHandler} to="/">
Home
</Link>
</div>
</Router>
);
}
export default App;
In the above example, we are disabling a Link by calling the event.preventDefault()
method in the onClick event handler function.
Conditionally rendering the Link component
We can conditionally render a link component as given below example.
import {useState} from 'react';
import {BrowserRouter as Router, Link} from 'react-router-dom';
function App() {
const [clickable, setClickable] = useState(true);
return (
<Router>
<div>
{clickable ? <Link to="/">Home</Link> : <span>Home</span>}
<button onClick={() => setClickable(!clickable)}>Toggle</button>
</div>
</Router>
);
}
export default App;
Here we are rendering <Link>
element if state clickable
is true
and, rendering <span>
if state clickable
is false
.
On datainfinities.com, Read articles all around JavaScript, React, Node.js, PHP, Laravel, and Shopify.
Related Blogs
Import and export may only appear at the top level
Unexpected default export of anonymous function
export 'withRouter' (imported as 'withRouter') was not found in 'react-router'
Using Redux Toolkit with React
Get the current route using React Router
How to Fix error:0308010C:digital envelope routines::unsupported
Find greatest common divisor (GCD) in JavaScript
Why useEffect is running twice in React?
Explore All Blogs