How to disable a link in reactjs?

Contain many issues on react-router, there is no support disabled attribute in Link Component, so you can try some with this issue:

1. onClick event

Use preventDefault() to handle onClick event.

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link onClick={e => e.preventDefault()} />
    );
  }
}

2. CSS's pointer-events attribute

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link className='disabled-link' />
    );
  }
}

/* css file */
.disable-link {
  pointer-events: none;
}

or you can use inline style

/* YourComponent.js */
class YourComponent extends React.Component {
  render() {
    return (
      <Link style={{ pointerEvents: 'none' }} />
    );
  }
}

What I used was method 2, it's more clearly for me on my project.


Another option is to have a function return 2 different links based on some condition....

const fnSomePath = () =>{
return somecondition ? `www.abc.xyz` : `#`
}

Then call the function where your link is being used:

<ListGroupItem>
  <NavLink to={{pathname: fnSomePath()}}>
      TEXT
   </NavLInk>
</ListGroupItem>

Tags:

Reactjs