Dobrado
Dobrado

Reputation: 63

Reload page if click to same path

:)

I'm trying to reload browser (with location.reload();) if user click in <Link> for the the same path, where it already.

Example:

I have a menu:

- Home - Contact - About

When user click in 'Contact', he go to '/contact'. But I he already in '/contact' and click in 'Contact' in menu, the page reload.

It's possible to do this?

What I'm trying:

<Link onClick={this.handleClick} to="contact">Contact</link>

handleClick(){
    var currentRoute = 'React-Route path';
    var linkRoute = 'link path';

    if (currentRoute === linkRoute)
        location.reload();
    } else {
        //do default transition
    }
}

But I don't figure what I need to declare in 'currentRoute' and 'linkRoute'. :(

Upvotes: 1

Views: 2985

Answers (2)

John Ruddell
John Ruddell

Reputation: 25842

You shouldn't reload the page. Thats a really bad idea. Instead disable the link like this:

if you are on the home page your links would look like this

<a href="/home" data-disabled="true">home</a>
<a href="/contact" data-disabled="false">contact</a>
<a href="/about" data-disabled="false">about</a>

Then in your handleClick() function you can just do this.

handleClick(e){
    e.preventDefault();
    var disabled = $(e.currentTarget).data('disabled');
    if (!disabled){ 
        //do redirect
    }
}

Basically have a data attribute on the link that specifies if it is disabled or not (only disabled if its on the current page) and then only redirect if its on a different page

Reloading the page on the exact same page will cause you to lose all state and process that the user has done, which doesn't need to happen. It also reduces traffic on your server for a new page load (aka any data you need to load on the page load you don't have to do again).

Upvotes: 1

Moe
Moe

Reputation: 1599

You can use window.location.href to get the current URL. Then you can do your comparison.

Upvotes: 0

Related Questions