Skip to content

Commit

Permalink
HAI-1248 Fix document scroll position in forms
Browse files Browse the repository at this point in the history
Fixed problem where form page in hanke form and cable report
application form would not be scrolled to top when entering
the form or changing form page.

Made it so that window.scrollTo(0, 0) is called when
MultipageForm component is mounted and unmounted and
also when changing form page.
  • Loading branch information
markohaarni committed Oct 10, 2023
1 parent bedc0f9 commit 5665870
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/common/hooks/useScrollToTop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useEffect } from 'react';

/**
* Scroll to top of window whenever component
* using this hook mounts and unmounts.
* Also return the scrollToTop function.
*/
function useScrollToTop() {
function scrollToTop() {
window.scrollTo(0, 0);
}

useEffect(() => {
scrollToTop();

return function cleanup() {
scrollToTop();
};
}, []);

return scrollToTop;
}

export default useScrollToTop;
3 changes: 3 additions & 0 deletions src/domain/forms/MultipageForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Text from '../../common/components/text/Text';
import { createStepReducer } from './formStepReducer';
import { Action, ACTION_TYPE, StepperStep } from './types';
import { SKIP_TO_ELEMENT_ID } from '../../common/constants/constants';
import useScrollToTop from '../../common/hooks/useScrollToTop';

function LoadingIndicator({ loadingText }: { loadingText?: string }) {
return (
Expand Down Expand Up @@ -77,6 +78,7 @@ const MultipageForm: React.FC<Props> = ({
notificationText,
}) => {
const locale = useLocale();
const scrollToTop = useScrollToTop();

const stepReducer = createStepReducer(formSteps.length);
const initialState = {
Expand All @@ -87,6 +89,7 @@ const MultipageForm: React.FC<Props> = ({

function handleStepChange(value: Action) {
function changeStep() {
scrollToTop();
dispatch(value);
if (onStepChange) {
onStepChange();
Expand Down
1 change: 1 addition & 0 deletions src/testUtils/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const AllTheProviders = ({ children }: Props) => {

const customRender = (ui: React.ReactElement, options: RenderOptions = {}, route = '/') => {
window.history.pushState({}, 'Test page', route);
window.scrollTo = function () {};
return {
user: userEvent.setup(),
...render(ui, {
Expand Down

0 comments on commit 5665870

Please sign in to comment.