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
.