Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove HREF attribute from anchor tag in ReactJS

Tags:

reactjs

I have the following render function. It creates a hyperlink when the component has a URL and leaves it empty otherwise.

render: function() {
    var url = this.state.url;
    if (url) {
        return <a href={url}>{this.props.children}</a>
    } else {
        return <a>{this.props.children}</a>
    }
},    

The problem is that once the HREF attribute has been set, React won't remove it. The else clause would lead to a tag that looks like this: <a data-reactid=".0.1" href="">.

I know I could just use a SPAN tag instead of A. For consistency sake though I would rather not.

like image 609
cleong Avatar asked Feb 27 '26 03:02

cleong


1 Answers

You could have the href be set to # and then add an onClick handler for it that has e.preventDefault() as the only thing for it. I would just use the span approach though.

like image 72
tirdadc Avatar answered Feb 28 '26 16:02

tirdadc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!