Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disabling navlink react router

I am using react router in and I want to disable the to attribute in a certain state. I passed empty string, but that doesn't disable the link instead it takes to the base route of the page. I even tried to pass null but that breaks the code. Is it even possible to do so?

<NavLink className="nav-link" to={this.state.role == 4 ? "/pages" : ""}></NavLink>
like image 724
Rizvan Avatar asked Mar 15 '18 10:03

Rizvan


People also ask

How do I turn off NavLink in react router?

You could try disabling the button with a custom click handler. Show activity on this post. Show activity on this post. React actually throws a warning if you set href to a boolean, but just leaving the href prop unspecified does the trick as well.

How do I turn off link tags in react?

Set the pointer events CSS property to none to disable a Link in React, e.g. <Link style={{pointerEvents: 'none'}}> . When the pointer events property of the link is set to none , the link is disabled.

What is NavLink in react?

In ReactJS, there are three different kinds of links. These are NavLink , Link , and a links, and they all serve different purposes. NavLink : This is used when you want to highlight the current or active link. This is used with the activeClassName attribute, which enables it.

What is the difference between link and NavLink?

What is the difference between NavLink and Link? The Link component is used to navigate the different routes on the site. But NavLink is used to add the style attributes to the active routes.


1 Answers

You could try disabling the button with a custom click handler.

handleClick = (e) => {
    const { linkDisabled } = this.state
    if(linkDisabled) e.preventDefault()
}

render() {
    return (
        <NavLink 
            onClick={this.handleClick} 
            className="nav-link" 
            to="/pages"
        >
            ...
        </NavLink>
    )   
}

You might want to add some css for when the button is disabled

Alternatively you could just not show the button at all

{
    this.state.linkDisabled ? 
        null :
        <NavLink className="nav-link" to="/pages"></NavLink>
}
like image 142
Stretch0 Avatar answered Sep 21 '22 16:09

Stretch0