From 3ffce552e126d9fcd01d28910a059f21b7163409 Mon Sep 17 00:00:00 2001 From: jpveooys <66470099+jpveooys@users.noreply.github.com> Date: Thu, 3 Mar 2022 15:05:41 +0000 Subject: [PATCH] fix(Dialog): Ensure IDs are stable between renders --- .../src/components/Dialog/Dialog.test.tsx | 35 +++++++++++++++++++ .../src/components/Dialog/Dialog.tsx | 6 ++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/packages/react-component-library/src/components/Dialog/Dialog.test.tsx b/packages/react-component-library/src/components/Dialog/Dialog.test.tsx index 16e74fe697..f489e3c197 100644 --- a/packages/react-component-library/src/components/Dialog/Dialog.test.tsx +++ b/packages/react-component-library/src/components/Dialog/Dialog.test.tsx @@ -94,4 +94,39 @@ describe('Modal', () => { }) }) }) + + describe('when the Dialog description changes', () => { + let initialTitleId: string + let initialDescriptionId: string + + const ExampleDialog = ({ + exampleDescription, + }: { + exampleDescription: string + }) => ( + + ) + + beforeEach(() => { + wrapper = render() + initialTitleId = wrapper.getByTestId('dialog-title').id + initialDescriptionId = wrapper.getByTestId('modal-body').id + + wrapper.rerender() + }) + + it('does not generate new a new title `id`', () => { + expect(wrapper.getByTestId('dialog-title')).toHaveAttribute( + 'id', + initialTitleId + ) + }) + + it('does not generate new a new description `id`', () => { + expect(wrapper.getByTestId('modal-body')).toHaveAttribute( + 'id', + initialDescriptionId + ) + }) + }) }) diff --git a/packages/react-component-library/src/components/Dialog/Dialog.tsx b/packages/react-component-library/src/components/Dialog/Dialog.tsx index cc7ab8df6e..1a6c9fe6db 100644 --- a/packages/react-component-library/src/components/Dialog/Dialog.tsx +++ b/packages/react-component-library/src/components/Dialog/Dialog.tsx @@ -2,11 +2,11 @@ import React from 'react' import { ComponentWithClass } from '../../common/ComponentWithClass' import { ButtonProps } from '../Button' -import { getId } from '../../helpers' import { StyledBody } from './partials/StyledBody' import { StyledDialog } from './partials/StyledDialog' import { StyledDescription } from './partials/StyledDescription' import { StyledTitle } from './partials/StyledTitle' +import { useExternalId } from '../../hooks/useExternalId' export interface DialogProps extends ComponentWithClass { /** @@ -55,8 +55,8 @@ export const Dialog: React.FC = ({ variant: 'secondary', } - const titleId = getId('dialog-title') - const descriptionId = getId('dialog-description') + const titleId = useExternalId('dialog-title') + const descriptionId = useExternalId('dialog-description') return (