Ver3.5 타입스크립트 접근성과 ARIA 속성 타입을 활용한포용적 웹 개발 완전 가이드

타입스크립트 접근성과 ARIA 속성 타입을 활용한
포용적 웹 개발 완전 가이드
모두를 위한 웹을 TypeScript로 안전하게 만드는 법 🦾
야 솔직히 말해서... 웹 접근성이라고 하면 대부분 개발자들이 "아 그거 나중에 하면 되지~" 하고 넘기는 경우 진짜 많잖아요 ㅋㅋㅋ 근데 이게 단순히 "장애인을 위한 배려" 수준이 아니라, 법적 의무이기도 하고 SEO에도 직결되고, 무엇보다 모든 사용자 경험의 질을 올려주는 핵심 요소예요.
그리고 TypeScript를 쓰면서 ARIA 속성을 타입 안전하게 다루는 방법을 제대로 아는 개발자가 생각보다 많지 않아요. 오늘은 이 두 가지를 완전히 연결해서, 타입스크립트로 접근성 있는 컴포넌트를 어떻게 만드는지 낱낱이 파헤쳐 볼게요! 🔥
1. 웹 접근성이 뭔데? 진짜로 알아야 하는 이유 🤔
웹 접근성(Web Accessibility)은 장애가 있는 사람들도 웹을 동등하게 이용할 수 있도록 보장하는 것이에요. 시각 장애, 청각 장애, 운동 장애, 인지 장애 등 다양한 상황에 있는 사용자들이 웹 콘텐츠에 접근할 수 있어야 한다는 개념이죠.
한국만 해도 약 265만 명의 등록 장애인이 있고, 고령화 사회로 접어들면서 일시적 장애(골절, 수술 후 회복 등)를 경험하는 사람까지 포함하면 그 수는 훨씬 많아져요.
이 사람들이 여러분이 만든 웹사이트를 못 쓴다면? 그건 단순한 UX 문제가 아니라 비즈니스 기회의 손실이에요!
법적 의무 - 이거 진짜 무시하면 안 됨
한국에서는 「장애인차별금지 및 권리구제 등에 관한 법률」에 따라 공공기관 및 일정 규모 이상의 민간 기업은 웹 접근성을 준수해야 해요. 미국의 ADA(Americans with Disabilities Act), 유럽의 EN 301 549 등 글로벌 기준도 있고요.
WCAG - 접근성의 바이블
W3C에서 만든 WCAG(Web Content Accessibility Guidelines)는 웹 접근성의 국제 표준이에요. 현재 WCAG 2.1이 주로 사용되고 WCAG 2.2가 최신 버전이에요.
WCAG는 4가지 원칙을 기반으로 해요:
2. ARIA가 뭔지 제대로 파헤쳐보자 🔍
ARIA는 Accessible Rich Internet Applications의 약자예요. W3C에서 만든 스펙으로, HTML 요소에 추가적인 의미론적 정보를 제공해서 보조 기술(스크린리더 등)이 더 잘 이해할 수 있게 해줘요.
예를 들어
<div>로 만든 커스텀 버튼은 스크린리더가 "버튼"이라고 인식 못 하는데, role="button"을 추가하면 인식할 수 있게 되는 거죠!
ARIA의 3가지 핵심 카테고리
① ARIA Roles (역할)
요소가 무엇인지 정의해요. HTML 시맨틱 태그가 없거나 부족할 때 사용해요.
// 나쁜 예 - 스크린리더가 이게 뭔지 모름
<div class="btn" onclick="submit()">제출</div>
// 좋은 예 - role로 역할 명시
<div role="button" tabindex="0" onclick="submit()">제출</div>
// 더 좋은 예 - 그냥 시맨틱 HTML 쓰기 (ARIA 필요 없음)
<button type="submit">제출</button>
② ARIA States (상태)
요소의 현재 상태를 나타내요. 동적으로 변할 수 있는 값들이에요.
// 체크박스 상태
<div role="checkbox" aria-checked="true">동의합니다</div>
// 확장/축소 상태
<button aria-expanded="false" aria-controls="menu">메뉴</button>
// 비활성화 상태
<button aria-disabled="true">제출 (처리 중)</button>
// 숨김 상태
<div aria-hidden="true">장식용 아이콘</div>
③ ARIA Properties (속성)
요소에 대한 추가 정보를 제공해요. 상태보다 덜 자주 변하는 특성들이에요.
// 레이블 연결
<input aria-label="검색어 입력" type="text" />
<input aria-labelledby="search-label" type="text" />
// 설명 추가
<input aria-describedby="password-hint" type="password" />
<p id="password-hint">8자 이상, 특수문자 포함</p>
// 필수 입력 표시
<input aria-required="true" type="email" />
// 오류 상태
<input aria-invalid="true" aria-errormessage="email-error" />
3. TypeScript에서 ARIA 타입 시스템 이해하기 💪
자 이제 진짜 본론이에요! TypeScript에서 ARIA 속성들은 어떻게 타입이 정의되어 있는지 알아볼게요. 이걸 제대로 이해하면 컴파일 타임에 접근성 오류를 잡을 수 있어요 - 진짜 개쩌는 기능이죠 ㅋㅋㅋ
React의 AriaAttributes 인터페이스
React의 타입 정의 패키지 @types/react에는 AriaAttributes 인터페이스가 정의되어 있어요. 이게 모든 ARIA 속성의 타입 기반이에요.
// @types/react에서 실제로 정의된 AriaAttributes (일부)
interface AriaAttributes {
/** 현재 요소가 제어하는 요소의 ID */
'aria-controls'?: string | undefined;
/** 현재 요소가 설명하는 요소의 ID */
'aria-describedby'?: string | undefined;
/** 현재 요소의 레이블 */
'aria-label'?: string | undefined;
/** 레이블 역할을 하는 요소의 ID */
'aria-labelledby'?: string | undefined;
/** 확장/축소 상태 */
'aria-expanded'?: Booleanish | undefined;
/** 선택 상태 */
'aria-selected'?: Booleanish | undefined;
/** 체크 상태 */
'aria-checked'?: boolean | 'false' | 'mixed' | 'true' | undefined;
/** 비활성화 상태 */
'aria-disabled'?: Booleanish | undefined;
/** 숨김 상태 */
'aria-hidden'?: Booleanish | undefined;
/** 필수 입력 여부 */
'aria-required'?: Booleanish | undefined;
/** 유효하지 않은 상태 */
'aria-invalid'?: boolean | 'false' | 'grammar' | 'spelling' | 'true' | undefined;
/** 라이브 리전 타입 */
'aria-live'?: 'assertive' | 'off' | 'polite' | undefined;
/** 역할 */
role?: AriaRole | undefined;
}
Booleanish는 TypeScript에서 boolean | 'true' | 'false'로 정의된 타입이에요. HTML 속성은 문자열이기 때문에 이런 타입이 필요해요!
AriaRole 타입 - 역할의 완전한 목록
TypeScript에서 AriaRole은 유니온 타입으로 정의되어 있어요. 이 덕분에 잘못된 role 값을 입력하면 바로 에러가 나요!
// AriaRole 타입 정의 (실제 @types/react 기반)
type AriaRole =
| 'alert'
| 'alertdialog'
| 'application'
| 'article'
| 'banner'
| 'button'
| 'cell'
| 'checkbox'
| 'columnheader'
| 'combobox'
| 'complementary'
| 'contentinfo'
| 'definition'
| 'dialog'
| 'directory'
| 'document'
| 'feed'
| 'figure'
| 'form'
| 'grid'
| 'gridcell'
| 'group'
| 'heading'
| 'img'
| 'link'
| 'list'
| 'listbox'
| 'listitem'
| 'log'
| 'main'
| 'marquee'
| 'math'
| 'menu'
| 'menubar'
| 'menuitem'
| 'menuitemcheckbox'
| 'menuitemradio'
| 'navigation'
| 'none'
| 'note'
| 'option'
| 'presentation'
| 'progressbar'
| 'radio'
| 'radiogroup'
| 'region'
| 'row'
| 'rowgroup'
| 'rowheader'
| 'scrollbar'
| 'search'
| 'searchbox'
| 'separator'
| 'slider'
| 'spinbutton'
| 'status'
| 'switch'
| 'tab'
| 'table'
| 'tablist'
| 'tabpanel'
| 'term'
| 'textbox'
| 'timer'
| 'toolbar'
| 'tooltip'
| 'tree'
| 'treegrid'
| 'treeitem'
| (string & {}); // 커스텀 role 허용
// 사용 예시
const MyComponent = () => {
// ✅ 올바른 사용
return <div role="button">클릭</div>;
// ❌ TypeScript 에러! 'buton'은 AriaRole에 없음
// return <div role="buton">클릭</div>;
};
커스텀 ARIA 타입 만들기
프로젝트에서 자주 쓰는 ARIA 패턴을 타입으로 정의해두면 팀 전체의 접근성 코드 품질이 올라가요. 이게 진짜 TypeScript의 힘이에요!
// aria-types.ts - 프로젝트 공통 ARIA 타입 정의
// 라이브 리전 타입
type AriaLiveValue = 'assertive' | 'off' | 'polite';
// aria-checked의 가능한 값들
type AriaCheckedValue = boolean | 'false' | 'mixed' | 'true';
// aria-invalid의 가능한 값들
type AriaInvalidValue = boolean | 'false' | 'grammar' | 'spelling' | 'true';
// 버튼 컴포넌트를 위한 ARIA 속성 타입
interface ButtonAriaProps {
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
'aria-expanded'?: boolean;
'aria-pressed'?: boolean | 'mixed';
'aria-disabled'?: boolean;
'aria-controls'?: string;
'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
}
// 입력 필드를 위한 ARIA 속성 타입
interface InputAriaProps {
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
'aria-required'?: boolean;
'aria-invalid'?: AriaInvalidValue;
'aria-errormessage'?: string;
'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both';
'aria-multiline'?: boolean;
'aria-readonly'?: boolean;
'aria-placeholder'?: string;
}
// 다이얼로그를 위한 ARIA 속성 타입
interface DialogAriaProps {
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
'aria-modal'?: boolean;
}
// 탭 컴포넌트를 위한 ARIA 속성 타입
interface TabAriaProps {
'aria-selected'?: boolean;
'aria-controls'?: string;
'aria-disabled'?: boolean;
}
export type {
AriaLiveValue,
AriaCheckedValue,
AriaInvalidValue,
ButtonAriaProps,
InputAriaProps,
DialogAriaProps,
TabAriaProps
};
4. 실전! TypeScript로 접근성 있는 컴포넌트 만들기 🛠️
이론은 충분히 했으니 이제 실제 코드로 가봐요! 자주 쓰는 UI 컴포넌트들을 TypeScript + ARIA로 제대로 만드는 방법을 보여드릴게요. 이거 보고 나면 "아 이렇게 하는 거구나!" 하고 바로 이해될 거예요 ㅋㅋㅋ
① 접근성 있는 버튼 컴포넌트
// AccessibleButton.tsx
import React, { ButtonHTMLAttributes, forwardRef } from 'react';
interface AccessibleButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
// 아이콘만 있는 버튼의 경우 반드시 aria-label 필요
'aria-label'?: string;
// 로딩 상태
isLoading?: boolean;
// 토글 버튼 여부
isToggle?: boolean;
// 토글 상태 (isToggle이 true일 때 사용)
isPressed?: boolean;
// 팝업 트리거 여부
hasPopup?: boolean | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
// 팝업 열림 상태
isExpanded?: boolean;
// 팝업이 제어하는 요소 ID
controlsId?: string;
}
const AccessibleButton = forwardRef<HTMLButtonElement, AccessibleButtonProps>(
(
{
children,
isLoading = false,
isToggle = false,
isPressed,
hasPopup,
isExpanded,
controlsId,
disabled,
'aria-label': ariaLabel,
...rest
},
ref
) => {
// 아이콘만 있는 버튼인데 aria-label이 없으면 경고
if (!children && !ariaLabel) {
console.warn(
'AccessibleButton: 텍스트가 없는 버튼에는 aria-label이 필요합니다!'
);
}
return (
<button
ref={ref}
disabled={disabled || isLoading}
aria-label={ariaLabel}
aria-busy={isLoading || undefined}
aria-pressed={isToggle ? isPressed : undefined}
aria-haspopup={hasPopup || undefined}
aria-expanded={hasPopup ? isExpanded : undefined}
aria-controls={controlsId}
aria-disabled={disabled || isLoading || undefined}
{...rest}
>
{isLoading ? (
<>
<span aria-hidden="true">⏳</span>
<span className="sr-only">처리 중...</span>
</>
) : (
children
)}
</button>
);
}
);
AccessibleButton.displayName = 'AccessibleButton';
export default AccessibleButton;
// 사용 예시
const Example = () => (
<div>
{/* 일반 버튼 */}
<AccessibleButton onClick={() => console.log('클릭!')}>
저장하기
</AccessibleButton>
{/* 아이콘 버튼 - aria-label 필수! */}
<AccessibleButton aria-label="닫기" onClick={() => {}}>
✕
</AccessibleButton>
{/* 로딩 버튼 */}
<AccessibleButton isLoading={true}>
제출하기
</AccessibleButton>
{/* 토글 버튼 */}
<AccessibleButton isToggle={true} isPressed={false}>
즐겨찾기
</AccessibleButton>
{/* 드롭다운 트리거 */}
<AccessibleButton
hasPopup="menu"
isExpanded={false}
controlsId="dropdown-menu"
>
메뉴 열기
</AccessibleButton>
</div>
);
② 접근성 있는 폼 입력 컴포넌트
// AccessibleInput.tsx
import React, { InputHTMLAttributes, useId } from 'react';
interface AccessibleInputProps extends InputHTMLAttributes<HTMLInputElement> {
label: string; // 레이블은 필수!
error?: string;
hint?: string;
isRequired?: boolean;
}
const AccessibleInput: React.FC<AccessibleInputProps> = ({
label,
error,
hint,
isRequired = false,
id: externalId,
...inputProps
}) => {
// React 18의 useId - 서버/클라이언트 ID 불일치 방지
const generatedId = useId();
const inputId = externalId || generatedId;
const errorId = `${inputId}-error`;
const hintId = `${inputId}-hint`;
// aria-describedby에 연결할 ID 목록 동적 생성
const describedByIds = [
hint ? hintId : null,
error ? errorId : null,
].filter(Boolean).join(' ');
return (
<div className="form-field">
<label htmlFor={inputId}>
{label}
{isRequired && (
<span aria-hidden="true" style={{ color: 'red' }}> *</span>
)}
</label>
{hint && (
<p id={hintId} className="hint-text">
{hint}
</p>
)}
<input
id={inputId}
aria-required={isRequired}
aria-invalid={error ? 'true' : undefined}
aria-describedby={describedByIds || undefined}
{...inputProps}
/>
{error && (
<p id={errorId} role="alert" className="error-text">
{error}
</p>
)}
</div>
);
};
export default AccessibleInput;
// 사용 예시
const LoginForm = () => {
const [email, setEmail] = React.useState('');
const [emailError, setEmailError] = React.useState('');
const validateEmail = (value: string) => {
if (!value.includes('@')) {
setEmailError('올바른 이메일 형식이 아닙니다.');
} else {
setEmailError('');
}
};
return (
<form>
<AccessibleInput
label="이메일"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
onBlur={(e) => validateEmail(e.target.value)}
error={emailError}
hint="예: user@example.com"
isRequired={true}
placeholder="이메일을 입력하세요"
/>
</form>
);
};
③ 접근성 있는 모달 다이얼로그
모달은 접근성에서 가장 까다로운 컴포넌트 중 하나예요. 포커스 트랩(Focus Trap), 키보드 탐색, ARIA 속성 등 신경 써야 할 게 많아요!
// AccessibleModal.tsx
import React, { useEffect, useRef, useCallback } from 'react';
interface AccessibleModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
titleId?: string;
description?: string;
descriptionId?: string;
children: React.ReactNode;
}
const AccessibleModal: React.FC<AccessibleModalProps> = ({
isOpen,
onClose,
title,
titleId = 'modal-title',
description,
descriptionId = 'modal-description',
children,
}) => {
const modalRef = useRef<HTMLDivElement>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
// 포커스 가능한 요소들 선택자
const FOCUSABLE_ELEMENTS = [
'a[href]',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(', ');
// 포커스 트랩 구현
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (!isOpen) return;
// ESC 키로 닫기
if (e.key === 'Escape') {
onClose();
return;
}
// Tab 키 포커스 트랩
if (e.key === 'Tab') {
const modal = modalRef.current;
if (!modal) return;
const focusableElements = modal.querySelectorAll<HTMLElement>(
FOCUSABLE_ELEMENTS
);
const firstElement = focusableElements[0];
const lastElement = focusableElements[focusableElements.length - 1];
if (e.shiftKey) {
// Shift+Tab: 역방향
if (document.activeElement === firstElement) {
e.preventDefault();
lastElement?.focus();
}
} else {
// Tab: 순방향
if (document.activeElement === lastElement) {
e.preventDefault();
firstElement?.focus();
}
}
}
},
[isOpen, onClose, FOCUSABLE_ELEMENTS]
);
useEffect(() => {
if (isOpen) {
// 모달 열릴 때 현재 포커스 저장
previousFocusRef.current = document.activeElement as HTMLElement;
// 모달 내 첫 번째 포커스 가능 요소로 포커스 이동
const modal = modalRef.current;
if (modal) {
const firstFocusable = modal.querySelector<HTMLElement>(
FOCUSABLE_ELEMENTS
);
firstFocusable?.focus();
}
// 배경 스크롤 방지
document.body.style.overflow = 'hidden';
document.addEventListener('keydown', handleKeyDown);
} else {
// 모달 닫힐 때 이전 포커스 복원
previousFocusRef.current?.focus();
document.body.style.overflow = '';
document.removeEventListener('keydown', handleKeyDown);
}
return () => {
document.removeEventListener('keydown', handleKeyDown);
document.body.style.overflow = '';
};
}, [isOpen, handleKeyDown, FOCUSABLE_ELEMENTS]);
if (!isOpen) return null;
return (
<>
{/* 배경 오버레이 */}
<div
aria-hidden="true"
onClick={onClose}
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.5)',
zIndex: 999,
}}
/>
{/* 모달 본체 */}
<div
ref={modalRef}
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
aria-describedby={description ? descriptionId : undefined}
style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
zIndex: 1000,
background: '#fff',
borderRadius: '12px',
padding: '24px',
maxWidth: '90vw',
maxHeight: '90vh',
overflow: 'auto',
}}
>
{/* 모달 헤더 */}
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<h2 id={titleId}>{title}</h2>
<button
onClick={onClose}
aria-label="모달 닫기"
style={{ background: 'none', border: 'none', cursor: 'pointer' }}
>
✕
</button>
</div>
{/* 설명 텍스트 */}
{description && (
<p id={descriptionId}>{description}</p>
)}
{/* 모달 내용 */}
{children}
</div>
</>
);
};
export default AccessibleModal;
aria-modal="true" 배경 콘텐츠를 숨김
aria-labelledby 모달 제목 연결
aria-describedby 모달 설명 연결
포커스 트랩 Tab 키가 모달 안에서만 순환
ESC 키 키보드로 닫기 가능
포커스 복원 닫힐 때 이전 위치로 포커스 복귀
5. 고급 패턴 - 타입 안전한 ARIA 유틸리티 만들기 🚀
이제 좀 더 심화된 내용으로 가볼게요! TypeScript의 제네릭과 조건부 타입을 활용해서 ARIA 속성을 더 안전하게 다루는 방법이에요. 이 정도 수준이면 팀에서 "TypeScript 잘 쓰는 사람"으로 인정받을 수 있어요 ㅋㅋㅋ
Role에 따른 ARIA 속성 제한 타입
특정 role에는 특정 ARIA 속성만 유효해요. 예를 들어 role="checkbox"에는 aria-checked가 필요하지만 role="button"에는 aria-pressed가 적절해요. 이걸 타입으로 강제할 수 있어요!
// aria-role-constraints.ts
// 각 role에 허용되는 ARIA 속성 매핑
type RoleAriaMap = {
button: {
'aria-pressed'?: boolean | 'mixed';
'aria-expanded'?: boolean;
'aria-haspopup'?: boolean | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
'aria-disabled'?: boolean;
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
'aria-controls'?: string;
};
checkbox: {
'aria-checked': boolean | 'mixed'; // 필수!
'aria-required'?: boolean;
'aria-readonly'?: boolean;
'aria-disabled'?: boolean;
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
};
combobox: {
'aria-expanded': boolean; // 필수!
'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both';
'aria-controls'?: string;
'aria-activedescendant'?: string;
'aria-required'?: boolean;
'aria-invalid'?: boolean | 'grammar' | 'spelling';
'aria-label'?: string;
'aria-labelledby'?: string;
};
dialog: {
'aria-modal'?: boolean;
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-describedby'?: string;
};
listbox: {
'aria-multiselectable'?: boolean;
'aria-required'?: boolean;
'aria-activedescendant'?: string;
'aria-label'?: string;
'aria-labelledby'?: string;
};
option: {
'aria-selected': boolean; // 필수!
'aria-disabled'?: boolean;
'aria-checked'?: boolean;
'aria-label'?: string;
};
slider: {
'aria-valuenow': number; // 필수!
'aria-valuemin': number; // 필수!
'aria-valuemax': number; // 필수!
'aria-valuetext'?: string;
'aria-orientation'?: 'horizontal' | 'vertical';
'aria-label'?: string;
'aria-labelledby'?: string;
};
tab: {
'aria-selected'?: boolean;
'aria-controls'?: string;
'aria-disabled'?: boolean;
'aria-label'?: string;
};
tabpanel: {
'aria-labelledby'?: string;
'aria-label'?: string;
};
};
// Role에 따른 ARIA 속성 타입 추출
type AriaPropsForRole<R extends keyof RoleAriaMap> = RoleAriaMap[R];
// 사용 예시
type CheckboxAriaProps = AriaPropsForRole<'checkbox'>;
// { 'aria-checked': boolean | 'mixed'; 'aria-required'?: boolean; ... }
type SliderAriaProps = AriaPropsForRole<'slider'>;
// { 'aria-valuenow': number; 'aria-valuemin': number; ... }
// 제네릭 컴포넌트에 적용
interface RoleBasedProps<R extends keyof RoleAriaMap> {
role: R;
ariaProps: AriaPropsForRole<R>;
children?: React.ReactNode;
}
function AccessibleElement<R extends keyof RoleAriaMap>({
role,
ariaProps,
children,
}: RoleBasedProps<R>) {
return (
<div role={role} {...ariaProps}>
{children}
</div>
);
}
// 사용 - TypeScript가 role에 맞는 ariaProps만 허용!
<AccessibleElement
role="checkbox"
ariaProps={{ 'aria-checked': true }} // ✅ OK
>
동의합니다
</AccessibleElement>
// ❌ 에러! slider role에는 aria-valuenow, min, max가 필수
// <AccessibleElement
// role="slider"
// ariaProps={{ 'aria-label': '볼륨' }}
// />
ARIA 라이브 리전 훅 만들기
동적으로 변하는 콘텐츠(알림, 상태 메시지 등)를 스크린리더에 알리려면 aria-live를 사용해야 해요. 이걸 React 훅으로 만들면 재사용하기 편해요!
// useAriaLive.ts
import { useState, useCallback, useRef, useEffect } from 'react';
type AriaLivePoliteness = 'polite' | 'assertive';
interface UseAriaLiveOptions {
politeness?: AriaLivePoliteness;
clearDelay?: number; // 메시지 자동 삭제 딜레이 (ms)
}
interface UseAriaLiveReturn {
message: string;
announce: (msg: string) => void;
clear: () => void;
AriaLiveRegion: React.FC;
}
function useAriaLive({
politeness = 'polite',
clearDelay = 5000,
}: UseAriaLiveOptions = {}): UseAriaLiveReturn {
const [message, setMessage] = useState('');
const timerRef = useRef<ReturnType<typeof setTimeout>>();
const announce = useCallback(
(msg: string) => {
// 같은 메시지를 연속으로 보낼 때 스크린리더가 읽도록
// 잠깐 비웠다가 다시 설정
setMessage('');
// 비동기로 처리해야 스크린리더가 변화를 감지함
setTimeout(() => {
setMessage(msg);
}, 50);
// 자동 삭제
if (clearDelay > 0) {
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = setTimeout(() => {
setMessage('');
}, clearDelay);
}
},
[clearDelay]
);
const clear = useCallback(() => {
setMessage('');
if (timerRef.current) clearTimeout(timerRef.current);
}, []);
useEffect(() => {
return () => {
if (timerRef.current) clearTimeout(timerRef.current);
};
}, []);
// 시각적으로 숨겨진 라이브 리전 컴포넌트
const AriaLiveRegion: React.FC = () => (
<div
aria-live={politeness}
aria-atomic="true"
aria-relevant="additions text"
style={{
position: 'absolute',
width: '1px',
height: '1px',
padding: 0,
margin: '-1px',
overflow: 'hidden',
clip: 'rect(0, 0, 0, 0)',
whiteSpace: 'nowrap',
border: 0,
}}
>
{message}
</div>
);
return { message, announce, clear, AriaLiveRegion };
}
export default useAriaLive;
// 사용 예시
const ShoppingCart = () => {
const { announce, AriaLiveRegion } = useAriaLive({ politeness: 'polite' });
const [cartCount, setCartCount] = useState(0);
const addToCart = (itemName: string) => {
setCartCount(prev => prev + 1);
// 스크린리더에 알림
announce(`${itemName}이(가) 장바구니에 추가되었습니다. 현재 ${cartCount + 1}개`);
};
return (
<div>
{/* 라이브 리전은 항상 DOM에 있어야 함! */}
<AriaLiveRegion />
<button onClick={() => addToCart('TypeScript 강의')}>
장바구니 담기
</button>
<span aria-label={`장바구니 ${cartCount}개`}>
🛒 {cartCount}
</span>
</div>
);
};
6. 접근성 테스팅 - TypeScript와 함께하는 자동화 🧪
코드 작성도 중요하지만 테스트로 접근성을 검증하는 것도 엄청 중요해요! TypeScript 환경에서 접근성 테스트를 자동화하는 방법을 알아볼게요.
jest-axe로 자동화 테스트
jest-axe는 axe-core 엔진을 Jest와 통합해서 접근성 위반을 자동으로 감지해줘요. TypeScript와 완벽하게 호환돼요!
// 설치
// npm install --save-dev jest-axe @types/jest-axe
// AccessibleButton.test.tsx
import React from 'react';
import { render } from '@testing-library/react';
import { axe, toHaveNoViolations } from 'jest-axe';
import AccessibleButton from './AccessibleButton';
// jest-axe 매처 확장
expect.extend(toHaveNoViolations);
describe('AccessibleButton 접근성 테스트', () => {
test('기본 버튼 - 접근성 위반 없음', async () => {
const { container } = render(
<AccessibleButton>저장하기</AccessibleButton>
);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
test('아이콘 버튼 - aria-label 있을 때 접근성 위반 없음', async () => {
const { container } = render(
<AccessibleButton aria-label="닫기">✕</AccessibleButton>
);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
test('로딩 버튼 - 접근성 위반 없음', async () => {
const { container } = render(
<AccessibleButton isLoading={true}>제출</AccessibleButton>
);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
// AccessibleInput.test.tsx
describe('AccessibleInput 접근성 테스트', () => {
test('레이블 있는 입력 - 접근성 위반 없음', async () => {
const { container } = render(
<AccessibleInput
label="이메일"
type="email"
isRequired={true}
/>
);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
test('오류 상태 입력 - 접근성 위반 없음', async () => {
const { container } = render(
<AccessibleInput
label="이메일"
type="email"
error="올바른 이메일 형식이 아닙니다"
/>
);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
Testing Library로 키보드 탐색 테스트
// modal.test.tsx
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import AccessibleModal from './AccessibleModal';
describe('AccessibleModal 키보드 접근성', () => {
const ModalWrapper = ({ isOpen }: { isOpen: boolean }) => (
<div>
<button id="trigger">모달 열기</button>
<AccessibleModal
isOpen={isOpen}
onClose={() => {}}
title="테스트 모달"
>
<button>첫 번째 버튼</button>
<button>두 번째 버튼</button>
<input type="text" placeholder="입력 필드" />
</AccessibleModal>
</div>
);
test('모달 열릴 때 첫 번째 포커스 가능 요소로 포커스 이동', () => {
render(<ModalWrapper isOpen={true} />);
// 첫 번째 포커스 가능 요소 (닫기 버튼 또는 첫 번째 버튼)
const firstButton = screen.getByText('첫 번째 버튼');
expect(document.activeElement).toBe(firstButton);
});
test('ESC 키로 모달 닫기', () => {
const onClose = jest.fn();
render(
<AccessibleModal
isOpen={true}
onClose={onClose}
title="테스트"
>
<button>버튼</button>
</AccessibleModal>
);
fireEvent.keyDown(document, { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(1);
});
test('role="dialog" 속성 확인', () => {
render(
<AccessibleModal isOpen={true} onClose={() => {}} title="테스트">
<p>내용</p>
</AccessibleModal>
);
const dialog = screen.getByRole('dialog');
expect(dialog).toBeInTheDocument();
expect(dialog).toHaveAttribute('aria-modal', 'true');
});
test('Tab 키 포커스 트랩 동작', async () => {
const user = userEvent.setup();
render(
<AccessibleModal isOpen={true} onClose={() => {}} title="테스트">
<button>버튼1</button>
<button>버튼2</button>
</AccessibleModal>
);
const button1 = screen.getByText('버튼1');
const button2 = screen.getByText('버튼2');
button1.focus();
await user.tab();
expect(document.activeElement).toBe(button2);
// 마지막 요소에서 Tab 누르면 첫 번째로 돌아와야 함
await user.tab();
// 닫기 버튼이 있다면 그쪽으로, 없다면 button1으로
expect(document.activeElement).not.toBe(document.body);
});
});
ESLint 접근성 플러그인 설정
코드 작성 단계에서부터 접근성 문제를 잡으려면 ESLint 플러그인을 사용해요!
// 설치
// npm install --save-dev eslint-plugin-jsx-a11y
// .eslintrc.js
module.exports = {
extends: [
'plugin:jsx-a11y/recommended',
// 더 엄격한 규칙을 원하면:
// 'plugin:jsx-a11y/strict',
],
plugins: ['jsx-a11y'],
rules: {
// 인터랙티브 요소에 키보드 이벤트 필수
'jsx-a11y/click-events-have-key-events': 'error',
// 인터랙티브 요소에 role 필수
'jsx-a11y/no-static-element-interactions': 'error',
// img에 alt 필수
'jsx-a11y/alt-text': 'error',
// label과 input 연결 필수
'jsx-a11y/label-has-associated-control': 'error',
// anchor에 콘텐츠 필수
'jsx-a11y/anchor-has-content': 'error',
// tabIndex 값 제한
'jsx-a11y/tabindex-no-positive': 'error',
// aria-* 속성 유효성 검사
'jsx-a11y/aria-props': 'error',
'jsx-a11y/aria-proptypes': 'error',
'jsx-a11y/aria-unsupported-elements': 'error',
// role 유효성 검사
'jsx-a11y/aria-role': ['error', { ignoreNonDOM: true }],
},
};
7. 실전 패턴 - 자주 쓰는 UI 컴포넌트 접근성 완성하기 🎨
① 접근성 있는 탭 컴포넌트
탭은 ARIA 패턴 중에서도 꽤 복잡한 편이에요. WAI-ARIA 탭 패턴을 TypeScript로 완벽하게 구현해볼게요!
// AccessibleTabs.tsx
import React, { useState, useRef, useCallback } from 'react';
interface Tab {
id: string;
label: string;
content: React.ReactNode;
disabled?: boolean;
}
interface AccessibleTabsProps {
tabs: Tab[];
defaultTabId?: string;
onChange?: (tabId: string) => void;
orientation?: 'horizontal' | 'vertical';
}
const AccessibleTabs: React.FC<AccessibleTabsProps> = ({
tabs,
defaultTabId,
onChange,
orientation = 'horizontal',
}) => {
const [activeTabId, setActiveTabId] = useState(
defaultTabId || tabs[0]?.id
);
const tabListRef = useRef<HTMLDivElement>(null);
const handleTabChange = useCallback(
(tabId: string) => {
setActiveTabId(tabId);
onChange?.(tabId);
},
[onChange]
);
// 키보드 탐색 처리
const handleKeyDown = useCallback(
(e: React.KeyboardEvent, currentIndex: number) => {
const enabledTabs = tabs.filter(tab => !tab.disabled);
const currentEnabledIndex = enabledTabs.findIndex(
tab => tab.id === tabs[currentIndex].id
);
let nextIndex: number | null = null;
const isHorizontal = orientation === 'horizontal';
const prevKey = isHorizontal ? 'ArrowLeft' : 'ArrowUp';
const nextKey = isHorizontal ? 'ArrowRight' : 'ArrowDown';
if (e.key === nextKey) {
nextIndex = (currentEnabledIndex + 1) % enabledTabs.length;
} else if (e.key === prevKey) {
nextIndex = (currentEnabledIndex - 1 + enabledTabs.length) % enabledTabs.length;
} else if (e.key === 'Home') {
nextIndex = 0;
} else if (e.key === 'End') {
nextIndex = enabledTabs.length - 1;
}
if (nextIndex !== null) {
e.preventDefault();
const nextTab = enabledTabs[nextIndex];
handleTabChange(nextTab.id);
// 포커스도 이동
const tabList = tabListRef.current;
if (tabList) {
const tabButton = tabList.querySelector<HTMLButtonElement>(
`[data-tab-id="${nextTab.id}"]`
);
tabButton?.focus();
}
}
},
[tabs, orientation, handleTabChange]
);
const activeTab = tabs.find(tab => tab.id === activeTabId);
return (
<div className="tabs-container">
{/* 탭 목록 */}
<div
ref={tabListRef}
role="tablist"
aria-orientation={orientation}
style={{
display: 'flex',
flexDirection: orientation === 'vertical' ? 'column' : 'row',
borderBottom: orientation === 'horizontal' ? '2px solid #e5e7eb' : 'none',
borderRight: orientation === 'vertical' ? '2px solid #e5e7eb' : 'none',
}}
>
{tabs.map((tab, index) => (
<button
key={tab.id}
role="tab"
id={`tab-${tab.id}`}
data-tab-id={tab.id}
aria-selected={activeTabId === tab.id}
aria-controls={`tabpanel-${tab.id}`}
aria-disabled={tab.disabled}
tabIndex={activeTabId === tab.id ? 0 : -1}
disabled={tab.disabled}
onClick={() => !tab.disabled && handleTabChange(tab.id)}
onKeyDown={(e) => handleKeyDown(e, index)}
style={{
padding: '10px 20px',
border: 'none',
background: 'none',
cursor: tab.disabled ? 'not-allowed' : 'pointer',
borderBottom: activeTabId === tab.id && orientation === 'horizontal'
? '2px solid #7c3aed'
: '2px solid transparent',
color: activeTabId === tab.id ? '#7c3aed' : '#6b7280',
fontWeight: activeTabId === tab.id ? '600' : '400',
opacity: tab.disabled ? 0.5 : 1,
}}
>
{tab.label}
</button>
))}
</div>
{/* 탭 패널들 */}
{tabs.map(tab => (
<div
key={tab.id}
role="tabpanel"
id={`tabpanel-${tab.id}`}
aria-labelledby={`tab-${tab.id}`}
hidden={activeTabId !== tab.id}
tabIndex={0}
style={{ padding: '20px 0' }}
>
{tab.content}
</div>
))}
</div>
);
};
export default AccessibleTabs;
// 사용 예시
const TabExample = () => (
<AccessibleTabs
tabs={[
{
id: 'profile',
label: '프로필',
content: <p>프로필 내용</p>,
},
{
id: 'settings',
label: '설정',
content: <p>설정 내용</p>,
},
{
id: 'billing',
label: '결제',
content: <p>결제 내용</p>,
disabled: true,
},
]}
onChange={(tabId) => console.log('탭 변경:', tabId)}
/>
);
② 접근성 있는 드롭다운 메뉴
// AccessibleDropdown.tsx
import React, { useState, useRef, useEffect, useCallback } from 'react';
interface DropdownItem {
id: string;
label: string;
onClick: () => void;
disabled?: boolean;
icon?: string;
}
interface AccessibleDropdownProps {
trigger: string;
items: DropdownItem[];
id: string;
}
const AccessibleDropdown: React.FC<AccessibleDropdownProps> = ({
trigger,
items,
id,
}) => {
const [isOpen, setIsOpen] = useState(false);
const [focusedIndex, setFocusedIndex] = useState(-1);
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLUListElement>(null);
const menuId = `${id}-menu`;
const enabledItems = items.filter(item => !item.disabled);
const closeMenu = useCallback(() => {
setIsOpen(false);
setFocusedIndex(-1);
triggerRef.current?.focus();
}, []);
// 외부 클릭 감지
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (
menuRef.current &&
!menuRef.current.contains(e.target as Node) &&
!triggerRef.current?.contains(e.target as Node)
) {
closeMenu();
}
};
if (isOpen) {
document.addEventListener('mousedown', handleClickOutside);
}
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isOpen, closeMenu]);
const handleTriggerKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown' || e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setIsOpen(true);
setFocusedIndex(0);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setIsOpen(true);
setFocusedIndex(enabledItems.length - 1);
}
};
const handleMenuKeyDown = (e: React.KeyboardEvent) => {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setFocusedIndex(prev =>
prev < enabledItems.length - 1 ? prev + 1 : 0
);
break;
case 'ArrowUp':
e.preventDefault();
setFocusedIndex(prev =>
prev > 0 ? prev - 1 : enabledItems.length - 1
);
break;
case 'Home':
e.preventDefault();
setFocusedIndex(0);
break;
case 'End':
e.preventDefault();
setFocusedIndex(enabledItems.length - 1);
break;
case 'Escape':
closeMenu();
break;
case 'Tab':
closeMenu();
break;
}
};
// 포커스 인덱스 변경 시 실제 DOM 포커스 이동
useEffect(() => {
if (isOpen && focusedIndex >= 0) {
const menuItems = menuRef.current?.querySelectorAll<HTMLElement>(
'[role="menuitem"]:not([aria-disabled="true"])'
);
menuItems?.[focusedIndex]?.focus();
}
}, [focusedIndex, isOpen]);
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
{/* 트리거 버튼 */}
<button
ref={triggerRef}
id={id}
aria-haspopup="menu"
aria-expanded={isOpen}
aria-controls={menuId}
onClick={() => setIsOpen(prev => !prev)}
onKeyDown={handleTriggerKeyDown}
>
{trigger}
<span aria-hidden="true"> {isOpen ? '▲' : '▼'}</span>
</button>
{/* 드롭다운 메뉴 */}
{isOpen && (
<ul
ref={menuRef}
role="menu"
id={menuId}
aria-labelledby={id}
onKeyDown={handleMenuKeyDown}
style={{
position: 'absolute',
top: '100%',
left: 0,
background: '#fff',
border: '1px solid #e5e7eb',
borderRadius: '8px',
padding: '4px 0',
minWidth: '160px',
boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
listStyle: 'none',
margin: 0,
zIndex: 100,
}}
>
{items.map((item) => (
<li key={item.id} role="none">
<button
role="menuitem"
aria-disabled={item.disabled}
disabled={item.disabled}
onClick={() => {
if (!item.disabled) {
item.onClick();
closeMenu();
}
}}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
width: '100%',
padding: '8px 16px',
border: 'none',
background: 'none',
cursor: item.disabled ? 'not-allowed' : 'pointer',
opacity: item.disabled ? 0.5 : 1,
textAlign: 'left',
}}
>
{item.icon && <span aria-hidden="true">{item.icon}</span>}
{item.label}
</button>
</li>
))}
</ul>
)}
</div>
);
};
8. 접근성 디버깅 도구와 실무 팁 🔧
코드를 잘 짰다고 끝이 아니에요! 실제로 접근성이 제대로 동작하는지 확인하는 도구들을 알아볼게요. 재능넷 같은 플랫폼에서 다양한 사용자들이 서비스를 이용한다는 걸 생각하면, 이 단계가 얼마나 중요한지 알 수 있어요.
브라우저 개발자 도구 활용
확인 포인트:
- Computed Properties: 실제로 적용된 ARIA 속성들
- Name: 스크린리더가 읽을 이름
- Role: 요소의 역할
- State: 현재 상태 (checked, expanded 등)
접근성 검사 도구들
axe DevTools (Chrome 확장)
가장 많이 쓰는 접근성 검사 도구. 자동으로 WCAG 위반 감지
WAVE (웹/확장)
시각적으로 접근성 문제를 표시해줌
Lighthouse (Chrome 내장)
접근성 점수 + 개선 방법 제시
Accessibility Insights (Microsoft)
자동 + 수동 검사 모두 지원
자동화 도구는 전체 접근성 문제의
약 30~40%만 감지해요!
나머지 60~70%는 실제 스크린리더로
직접 테스트해야 발견 가능해요.
도구 점수 100점 = 완벽한 접근성
이 아니라는 걸 명심하세요!
TypeScript 접근성 유틸리티 함수 모음
// a11y-utils.ts - 접근성 유틸리티 함수 모음
/**
* 시각적으로 숨기지만 스크린리더에는 읽히는 CSS 클래스용 스타일
* "sr-only" 패턴
*/
export const srOnlyStyles: React.CSSProperties = {
position: 'absolute',
width: '1px',
height: '1px',
padding: 0,
margin: '-1px',
overflow: 'hidden',
clip: 'rect(0, 0, 0, 0)',
whiteSpace: 'nowrap',
borderWidth: 0,
};
/**
* 스크린리더 전용 텍스트 컴포넌트
*/
export const VisuallyHidden: React.FC<{ children: React.ReactNode }> = ({
children,
}) => <span style={srOnlyStyles}>{children}</span>;
/**
* 고유 ID 생성 (useId 미사용 환경용)
*/
let idCounter = 0;
export const generateId = (prefix: string = 'a11y'): string => {
return `${prefix}-${++idCounter}`;
};
/**
* 포커스 가능한 요소 목록 가져오기
*/
export const getFocusableElements = (
container: HTMLElement
): HTMLElement[] => {
const selector = [
'a[href]',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
'[contenteditable="true"]',
].join(', ');
return Array.from(container.querySelectorAll<HTMLElement>(selector));
};
/**
* 첫 번째 포커스 가능 요소로 포커스 이동
*/
export const focusFirstElement = (container: HTMLElement): void => {
const elements = getFocusableElements(container);
elements[0]?.focus();
};
/**
* 색상 대비 비율 계산 (WCAG 기준)
* @param foreground - 전경색 (hex)
* @param background - 배경색 (hex)
* @returns 대비 비율 (1:1 ~ 21:1)
*/
export const calculateContrastRatio = (
foreground: string,
background: string
): number => {
const getLuminance = (hex: string): number => {
const rgb = parseInt(hex.slice(1), 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = rgb & 0xff;
const toLinear = (c: number): number => {
const sRGB = c / 255;
return sRGB <= 0.03928
? sRGB / 12.92
: Math.pow((sRGB + 0.055) / 1.055, 2.4);
};
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b);
};
const l1 = getLuminance(foreground);
const l2 = getLuminance(background);
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
};
/**
* WCAG 대비 비율 검사
*/
export const checkContrastRatio = (
foreground: string,
background: string,
level: 'AA' | 'AAA' = 'AA',
isLargeText: boolean = false
): { passes: boolean; ratio: number; required: number } => {
const ratio = calculateContrastRatio(foreground, background);
let required: number;
if (level === 'AAA') {
required = isLargeText ? 4.5 : 7;
} else {
required = isLargeText ? 3 : 4.5;
}
return {
passes: ratio >= required,
ratio: Math.round(ratio * 100) / 100,
required,
};
};
// 사용 예시
const result = checkContrastRatio('#ffffff', '#7c3aed');
console.log(result);
// { passes: true, ratio: 7.23, required: 4.5 }
/**
* 키보드 이벤트 핸들러 생성 유틸리티
* 클릭 이벤트를 키보드로도 동작하게 만들기
*/
export const createKeyboardHandler = (
onClick: () => void,
keys: string[] = ['Enter', ' ']
) => (e: React.KeyboardEvent): void => {
if (keys.includes(e.key)) {
e.preventDefault();
onClick();
}
};
9. 자주 하는 실수와 안티패턴 ❌
이론과 실전 코드를 다 봤으니, 이제 개발자들이 자주 저지르는 실수들을 짚어볼게요. 이거 알고 나면 코드 리뷰할 때 바로 잡아낼 수 있어요 ㅋㅋㅋ
실수 1: ARIA 남용 (ARIA Abuse)
// 시맨틱 HTML이 있는데 굳이 ARIA 사용
<nav role="navigation">
<ul role="list">
<li role="listitem">메뉴</li>
</ul>
</nav>
// 이미 button인데 role 추가
<button role="button">
클릭
</button>
// 시맨틱 HTML 자체가 역할을 가짐
<nav>
<ul>
<li>메뉴</li>
</ul>
</nav>
// button은 이미 button role
<button>
클릭
</button>
실수 2: aria-label과 텍스트 중복
// 텍스트가 있는데 aria-label로 다른 내용
<button aria-label="제출 버튼">
저장하기
</button>
// 스크린리더: "제출 버튼" 읽음
// 시각 사용자: "저장하기" 봄 → 불일치!
// 텍스트가 있으면 aria-label 불필요
<button>
저장하기
</button>
// 아이콘만 있을 때 aria-label 사용
<button aria-label="저장하기">
💾
</button>
실수 3: tabIndex 양수 사용
// tabIndex 양수는 탭 순서를 망침!
<button tabIndex={3}>첫 번째</button>
<button tabIndex={1}>두 번째</button>
<button tabIndex={2}>세 번째</button>
// 실제 탭 순서: 두 번째 → 세 번째 → 첫 번째
// 완전 혼란스러움 😱
// tabIndex는 0 또는 -1만 사용
// 0: 자연스러운 탭 순서에 포함
// -1: 탭 순서에서 제외 (프로그래밍으로만 포커스)
<button tabIndex={0}>첫 번째</button>
<button tabIndex={0}>두 번째</button>
<button tabIndex={0}>세 번째</button>
// DOM 순서대로 탭 이동 ✅
실수 4: aria-hidden으로 포커스 가능 요소 숨기기
// ❌ 절대 하면 안 되는 패턴!
// aria-hidden="true"인 요소 안에 포커스 가능 요소가 있으면
// 스크린리더는 못 읽는데 키보드로는 접근 가능한 모순 발생
<div aria-hidden="true">
<button>이 버튼은 스크린리더가 못 읽지만 Tab으로 접근 가능</button>
</div>
// ✅ 올바른 방법
// 방법 1: 포커스 불가능하게 만들기
<div aria-hidden="true">
<button tabIndex={-1} aria-hidden="true">장식용 버튼</button>
</div>
// 방법 2: 아예 DOM에서 제거
{!isHidden && <button>버튼</button>}
// 방법 3: visibility: hidden 또는 display: none 사용
// (이 경우 자동으로 스크린리더에서도 숨겨지고 포커스도 불가)
<div style={{ display: 'none' }}>
<button>완전히 숨겨진 버튼</button>
</div>
실수 5: 동적 콘텐츠 변경 알림 누락
// ❌ 나쁜 예 - 상태 변경을 스크린리더에 알리지 않음
const [isLiked, setIsLiked] = useState(false);
<button onClick={() => setIsLiked(!isLiked)}>
{isLiked ? '❤️' : '🤍'}
</button>
// 스크린리더 사용자는 상태가 바뀐 걸 모름!
// ✅ 좋은 예 - aria-pressed와 aria-label로 상태 전달
<button
aria-pressed={isLiked}
aria-label={isLiked ? '좋아요 취소' : '좋아요'}
onClick={() => setIsLiked(!isLiked)}
>
{isLiked ? '❤️' : '🤍'}
</button>
// 스크린리더: "좋아요, 토글 버튼, 눌림" 또는 "좋아요, 토글 버튼, 안 눌림"
10. 접근성 컴포넌트 라이브러리 활용하기 📦
처음부터 모든 걸 직접 만들 필요는 없어요! 이미 접근성이 잘 구현된 라이브러리들을 활용하면 개발 속도를 높이면서도 접근성을 보장할 수 있어요.
비스타일 접근성 컴포넌트. 완전한 TypeScript 지원. Dialog, Dropdown, Tabs 등 모든 WAI-ARIA 패턴 구현
2. Headless UI (Tailwind Labs)
React + Vue 지원. TypeScript 완벽 지원. 스타일 없이 접근성만 제공
3. React Aria (Adobe)
Adobe에서 만든 접근성 훅 모음. 가장 완성도 높은 접근성 구현
4. Ariakit
WAI-ARIA 패턴 기반 컴포넌트. TypeScript 지원
5. shadcn/ui
Radix UI 기반 + Tailwind CSS. 최근 가장 인기 있는 컴포넌트 라이브러리
Radix UI 사용 예시
// npm install @radix-ui/react-dialog @radix-ui/react-tabs
// Radix UI Dialog - 접근성 완벽 지원
import * as Dialog from '@radix-ui/react-dialog';
const RadixModal = () => (
<Dialog.Root>
<Dialog.Trigger asChild>
<button>모달 열기</button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay style={{ background: 'rgba(0,0,0,0.5)', position: 'fixed', inset: 0 }} />
<Dialog.Content
style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
background: '#fff',
padding: '24px',
borderRadius: '12px',
}}
>
<Dialog.Title>모달 제목</Dialog.Title>
<Dialog.Description>모달 설명</Dialog.Description>
<p>모달 내용</p>
<Dialog.Close asChild>
<button aria-label="닫기">✕</button>
</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
);
// Radix가 자동으로 처리하는 것들:
// - role="dialog", aria-modal="true"
// - aria-labelledby, aria-describedby 연결
// - 포커스 트랩
// - ESC 키 닫기
// - 포커스 복원
// - 배경 스크롤 방지
// Radix UI Tabs
import * as Tabs from '@radix-ui/react-tabs';
const RadixTabs = () => (
<Tabs.Root defaultValue="tab1">
<Tabs.List aria-label="탭 목록">
<Tabs.Trigger value="tab1">탭 1</Tabs.Trigger>
<Tabs.Trigger value="tab2">탭 2</Tabs.Trigger>
</Tabs.List>
<Tabs.Content value="tab1">탭 1 내용</Tabs.Content>
<Tabs.Content value="tab2">탭 2 내용</Tabs.Content>
</Tabs.Root>
);
11. 마무리 - 포용적 개발 문화 만들기 🌍
기술적인 내용을 다 다뤘으니 마지막으로 좀 더 큰 그림을 얘기해볼게요. 접근성은 단순히 "기능 추가"가 아니라 개발 문화의 변화예요.
개발 단계에서 접근성을 추가하는 것보다 디자인 단계에서 고려하는 게 훨씬 효율적이에요.
2. 접근성 체크리스트를 PR 리뷰에 포함
코드 리뷰할 때 접근성 항목도 체크하는 문화를 만들어요.
3. 자동화 테스트 CI/CD에 통합
jest-axe, axe-core를 CI 파이프라인에 넣어서 접근성 회귀를 방지해요.
4. 실제 보조 기술 사용자 피드백 수집
가능하다면 스크린리더 사용자와 함께 테스트하는 게 가장 효과적이에요.
TypeScript가 접근성에 주는 진짜 가치
TypeScript를 쓰면서 ARIA 속성을 타입 안전하게 다루면 얻는 이점들을 정리해볼게요:
aria-checked="yes" 같은 실수를 TypeScript가 바로 잡아줘요.기억해야 할 핵심 원칙:
① 시맨틱 HTML 먼저, ARIA는 보완적으로
② 모든 인터랙티브 요소에 키보드 접근성 보장
③ 동적 콘텐츠 변경은 aria-live로 알림
④ 포커스 관리를 철저히 (모달, 드로어 등)
⑤ 자동화 테스트 + 실제 스크린리더 테스트 병행
TypeScript + ARIA = 모든 사용자를 위한 더 나은 웹 🌐
댓글 작성
이 글에 대한 여러분의 생각을 들려주세요
로그인이 필요합니다
댓글을 작성하려면 먼저 로그인해주세요.
댓글 0
지식인의 숲 - 지적 재산권 보호 고지
지적 재산권 보호 고지
- 저작권 및 소유권: 본 컨텐츠는 재능넷의 독점 AI 기술로 생성되었으며, 대한민국 저작권법 및 국제 저작권 협약에 의해 보호됩니다.
- AI 생성 컨텐츠의 법적 지위: 본 AI 생성 컨텐츠는 재능넷의 지적 창작물로 인정되며, 관련 법규에 따라 저작권 보호를 받습니다.
- 사용 제한: 재능넷의 명시적 서면 동의 없이 본 컨텐츠를 복제, 수정, 배포, 또는 상업적으로 활용하는 행위는 엄격히 금지됩니다.
- 데이터 수집 금지: 본 컨텐츠에 대한 무단 스크래핑, 크롤링, 및 자동화된 데이터 수집은 법적 제재의 대상이 됩니다.
- AI 학습 제한: 재능넷의 AI 생성 컨텐츠를 타 AI 모델 학습에 무단 사용하는 행위는 금지되며, 이는 지적 재산권 침해로 간주됩니다.
아직 댓글이 없습니다.