javascriptreactjshrefreact-router

Easier way to to disable link in React?


I want to disable Link in some condition:

render() {
    return (<li>{this.props.canClick ? 
        <Link to="/">Test</Link> : 
        <a>Test</a>}
    </li>)  
}

<Link> must specify to, so I can not disable <Link> and I have to use <a>


Solution

  • You could just set set the link's onClick property:

    render () {
      return(
        <li> 
        { 
          this.props.notClickable
          ? <Link to="/" className="disabledCursor" onClick={ (event) => event.preventDefault() }>Link</Link>
          : <Link to="/" className="notDisabled">Link</Link>
        }
        </li>
      );
    };
    

    Then disable the hover effect via css using the cursor property.

    .disabledCursor { 
      cursor: default;
    }
    

    I think that should do the trick?