Skip to content

Commit

Permalink
Fix initial page redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
kevin940726 committed Dec 13, 2021
1 parent bdb289a commit 1b50ad1
Showing 1 changed file with 18 additions and 2 deletions.
@@ -1,3 +1,8 @@
/**
* External dependencies
*/
import { Action } from 'history';

/**
* WordPress dependencies
*/
Expand All @@ -6,19 +11,30 @@ import { useRef, useEffect } from '@wordpress/element';
/**
* Internal dependencies
*/
import { useLocation } from './index';
import { useLocation, useHistory } from './index';

export default function useResetFocusOnRouteChange( targetRef ) {
const history = useHistory();
const location = useLocation();
const isInitialPageLoadRef = useRef( true );
const expectRedirectionRef = useRef( false );

useEffect( () => {
// Don't focus for initial page load.
if ( isInitialPageLoadRef.current ) {
isInitialPageLoadRef.current = false;
expectRedirectionRef.current = true;
return;
}
// Don't focus for the initial page redirection.
// TODO: This can be removed once #36873 is resolved.
if ( expectRedirectionRef.current ) {
expectRedirectionRef.current = false;
if ( history.action === Action.Replace ) {
return;
}
}

targetRef.current?.focus();
}, [ location, targetRef ] );
}, [ location, targetRef, history ] );
}

0 comments on commit 1b50ad1

Please sign in to comment.