Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a link in reactjs?

Tags:

reactjs

I have this in my reactjs app:

import Link from 'react-router/lib/Link'

Been trying to disable this link but this does not have the desired effect:

<Link disable={true}/>

It just renders it invisible. How can I disable( based on a condition) the reactjs Link?

like image 488
bier hier Avatar asked Mar 13 '17 02:03

bier hier


2 Answers

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.

like image 79
OA Wan Avatar answered Oct 29 '22 06:10

OA Wan


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>

like image 30
John Munyi Avatar answered Oct 29 '22 06:10

John Munyi