Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When link is clicked, default browser event isn't prevented #340

Closed
triallax opened this issue Oct 5, 2019 · 5 comments
Closed

When link is clicked, default browser event isn't prevented #340

triallax opened this issue Oct 5, 2019 · 5 comments

Comments

@triallax
Copy link

triallax commented Oct 5, 2019

Explanation:

When clicking a link, the page correctly changes to the matching route. However, immediately after that, I get a new page saying Cannot GET /foo

This issue occurs only when using the a tag instead of Link.

@pimdewit
Copy link
Contributor

This took me forever to debug, glad I'm not going crazy

@triallax
Copy link
Author

triallax commented Oct 16, 2019

I created this simple workaround for now. Put this in the component where you use the Router component:

useEffect(() => {
        function callback(event) {
            const target = event.target;
            if (
                target &&
                target.nodeName.toLowerCase() === 'a' &&
                !target.href.startsWith('mailto:')
            ) {
                if (event.stopImmediatePropagation) {
                    event.stopImmediatePropagation();
                }
                if (event.stopPropagation) {
                    event.stopPropagation();
                }
                event.preventDefault();
            }
        }
        window.addEventListener('click', callback);
        return () => {
            window.removeEventListener('click', callback);
        };
    }, []);

I didn't complicate it too much because my website isn't that complex anyways. Any suggestions are appreciated.

@jschill
Copy link

jschill commented Oct 18, 2019

I have the same issue. routeTo() returns false, so the event is not prevented.

function routeTo(url) {

Called from here

if (routeFromLink(t)) {

@developit
Copy link
Member

I just figured out what's causing this. In preact 10, Component.forceUpdate() is no longer synchronous. Unfortunately, preact-router is relying on synchronous updates in order to determine whether a clicked link was handled by any mounted routers. It invokes forceUpdate(), then immediately attempts to inspect a Boolean flag set by render():

preact-router/src/index.js

Lines 177 to 178 in f7dbe6d

this.forceUpdate();
return this._didRoute;

@developit
Copy link
Member

aaand we have a fix! #342

marvinhagemeister added a commit that referenced this issue Oct 21, 2019
Fix route handling in Preact 10 (fixes #340)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants