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?
Contain many issues on react-router , there is no support disabled attribute in Link Component, so you can try some with this issue :
Use preventDefault()
to handle onClick event.
/* YourComponent.js */
class YourComponent extends React.Component {
render() {
return (
<Link onClick={e => e.preventDefault()} />
);
}
}
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.
You could conditionally render something that looks like a disabled link based upon some state.
For instance in typescript:
export interface Location {
pathname: string;
search: string;
state: any;
hash: string;
key ?: string;
}
interface LinkProps {
to: string | Location
replace?:boolean
}
interface DisableLinkProps extends LinkProps {
enabled: boolean
linkText:string
}
export class DisableLink extends React.Component<DisableLinkProps, undefined> {
render() {
var element= this.props.enabled ? <span className="disableLinkDisabled">{this.props.linkText}</span> : <Link to={this.props.to} replace={this.props.replace}>{this.props.linkText}</Link>
return element;
}
}
interface DemoClassState {
linkEnabled:boolean
}
export class DemoClass extends React.Component<undefined, DemoClassState> {
constructor(props) {
super(props);
this.state = { linkEnabled:false }
}
toggleLinkEnabled = () => {
this.setState((prevState) => {
return {
linkEnabled: !prevState.linkEnabled
}
});
}
render() {
return <div>
<DisableLink enabled={this.state.linkEnabled} to="/somewhere" linkText="Some link" />
<button onClick={this.toggleLinkEnabled}>Toggle link enabled</button>
</div>
}
}
This is actually a bit tricky. And maybe even somewhat ill-advised.
https://css-tricks.com/how-to-disable-links/
The route (no pun intended) I took was to not render the link.
I composed a new component from react-router's Link
.
import React from 'react';
import { Link } from 'react-router-dom';
export default function ToggleableLink(props) {
const { disabled, ...rest } = props;
return disabled ? props.children : <Link {...rest}>{props.children}</Link>;
}
Usage:
<ToggleableLink disabled={!showTheLink}>Foobar</ToggleableLink>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.