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>
It is still possible to disable a link by following 3 steps: remove the href attribute so that it can no longer receive the focus. add a role="link" so that it is always considered a link by screen readers. add an attribute aria-disabled="true" so that it is indicated as being disabled.
To disable a Link if it's active in React Router, we set the to path of the Link 's pointer-events CSS property to none . to add the disabled-link class to the Link . to disable the mouse pointer we usually see over a link with pointer-events with none .
Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!
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?
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>)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With