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 <Link onClick={this.onClick.bind(this)} {...other}>{children}</Link>
}
}
export default withRouter(SafeLink);
You can then use your link as (any extra props from Link
would work):
<SafeLink className="some_class" to="/some_route">Link text</SafeLink>
React Router's Route
component has three different ways to render content based on the current route. While component
is most typically used to show a component only during a match, the children
component takes in a ({match}) => {return <stuff/>}
callback that can render things cased on match even when the routes don't match.
I've created a NavLink class that replaces a Link with a span and adds a class when its to
route is active.
class NavLink extends Component {
render() {
var { className, activeClassName, to, exact, ...rest } = this.props;
return(
<Route
path={to}
exact={exact}
children={({ match }) => {
if (match) {
return <span className={className + " " + activeClassName}>{this.props.children}</span>;
} else {
return <Link className={className} to={to} {...rest}/>;
}
}}
/>
);
}
}
Then create a navlink like so
<NavLink to="/dashboard" className="navlink" activeClassName="active">
React Router's NavLink does something similar, but that still allows the user to click into the link and push history.
If it fits your design, put a div on top of it, and manipulate the z-index.