Reputation: 103
How do I prevent default (event.preventDefault()) of a Link component in React if certain state changes, for example, if this.state.isActive is false, when I click the link, nothing happens. See code below:
`import { Link } from 'react-router';
return (
<div>
{<Link to={link}>
<img src={someImageUrl} alt={someImageName} />
</Link>}
</div>
);`
I am using React version 6.
Upvotes: 1
Views: 1983
Reputation: 3323
Simply give a onClick function to the Link
Yes it is possible
import { Link } from 'react-router';
const isActive = false;
customFunction(){
if(isActive){
this.prop.history.push(link)
}
}
return (
<div>
{<Link onClick={customFunction}>
<img src={someImageUrl} alt={someImageName} />
</Link>}
</div>
);
Upvotes: 1
Reputation: 312
If you don't want it to behave like a link at all, you can conditionally render it as a link or a span. For example:
{this.state.isActive ? (<Link to={link}>...</Link>):(<span>...</span>)}
Alternatively, if you don't mind having a link that doesn't go anywhere, you can do:
<Link to={this.state.isActive ? link : '#'}>...</Link>
Upvotes: 0
Reputation: 2104
You can by passing an onClick
function to the element wrapped inside the <Link />
tag:
import { Link } from 'react-router';
const prevent = e => {
e.preventDefault()
e.stopPropagation()
// do whatever
}
return (
<div>
{<Link to={link}>
<img src={someImageUrl} alt={someImageName} onClick={prevent}/>
</Link>}
</div>
);
EDIT: I misunderstood the question
Here is the real solution:
import { Link } from 'react-router';
const link = isActive ? "/somePath" : null
return (
<div>
{<Link to={link}>
<img src={someImageUrl} alt={someImageName} />
</Link>}
</div>
);
Upvotes: 2