I want to disable Link
in some condition:
render() {
return ({this.props.canClick ?
Test
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?
In short easier way to disable link in React?
<Link to="#">Text</Link>
Your code already seems quite clean and slim. Not sure why you want an "easier" way. I'd do it exactly how you're doing it.
However, here are a few alternatives:
This one is probably as short and sweet as you can get it:
render() {
return (<li>
<Link to="/" style={this.props.canClick ? {pointerEvents: "none"} : null}>Test</Link>
</li>)
}
As an alternative, you could use a generic <a>
tag and add an onClick
listener for the condition. This is probably better suited if you have lots of links that you want to control their state because you could use the same function on all of them.
_handleClick = () => {
if(this.props.canClick) {
this.context.router.push("/");
}
}
render() {
return (
<li>
<a onClick={this._handleClick}>Test</a>});
</li>
);
}
The above will work assuming you are using context.router
. If not, add to your class:
static contextTypes = {
router: React.PropTypes.object
}
As I mentioned above, I still think your approach is the "best". You could replace the anchor tag with a span, to get rid of the styling for a disabled link (e.g pointer cursor, hover effects, etc).
render() {
return (<li>{this.props.canClick ?
<Link to="/">Test</Link> :
<span>Test</span>}
</li>)
}
Just making the URL null seems to do the trick:
const url = isDisabled ? null : 'http://www.stackoverflow.com';
return (
<a href={url}>Click Me</a>
);
Passing #
in to
prop to the Link should do the trick for you
You can define link as per your requirement. if you want to disable it just pass #
in props.link
render() {
return (<li><Link to={props.link}>Test</Link></li>);
}
A good solution is using onClick()
with event
object. just do this in your jsx:
<Link to='Everything' onClick={(e) => this._onClick(e)}
and in your _onClick
function:
_onClick = (e) => {
e.preventDefault()
}
Complete Example in React:
import React, { Component } from 'react'
import {Link} from 'react-router-dom'
export default class List extends Component {
_onClick = (e) => {
e.preventDefault()
}
render(){
return(
<div className='link-container'>
<Link to='Something' onClick={e => this._onClick(e)}
</div>
)
}
}