How can I disable a in react-router, if its URL already active? E.g. if my URL wouldn\'t change on a click on
I want to p
Another possibility is to disable the click event if clicking already on the same path. Here is a solution that works with react-router v4.
import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
class SafeLink extends Component {
onClick(event){
if(this.props.to === this.props.history.location.pathname){
event.preventDefault();
}
// Ensure that if we passed another onClick method as props, it will be called too
if(this.props.onClick){
this.props.onClick();
}
}
render() {
const { children, onClick, ...other } = this.props;
return {children}
}
}
export default withRouter(SafeLink);
You can then use your link as (any extra props from Link
would work):
Link text