🥯 애피타이저
처음 리액트 공식문서에서 useId라는 훅을 보았을 때 리액트에서 uuid를 대체하는 훅이 만들어진건가! 라는 생각으로 공부해보게 되었습니다. 하지만 공부해보니 uuid랑은 상관 없는 훅이었습니다.
이제 useId에 대해서 알아보겠습니다.
🍖 메인
const id = useId();
- useId 훅은 매개변수는 사용하지 않습니다.
- 고유 ID 문자열을 반환합니다.
- useId는 컴포넌트 최상단 혹은 훅에서만 호출이 가능합니다.
- 리스트의 Key로 사용하면 안됩니다.
useId 사용해보기
import { useId } from 'react';
const Input = ({labelText}) => {
return (
<div>
<label htmlFor='inputId'>{labelText}</label>
<input id='inputId' type="text" />
</div>
)
}
export default function Form() {
return (
<form>
<Input labelText={'User Name: '} />
<Input labelText={'User Email: '} />
<Input labelText={'User Password: '} />
</form>
);
}
Input 컴포넌트에서 label과 input을 연결시켜 사용하려고 id를 동일하게 설정했습니다.
하지만 Input 컴포넌트를 여러 개 사용하게 된다면 한 컴포넌트 안에 동일한 id를 가진 컴포넌트가 여러 개가 되고, 아래 그림과 같이 다른 label를 눌러도 첫 번째 label과 연결된 input에만 focus가 잡히게 됩니다.
import { useId } from 'react';
const Input = ({labelText}) => {
const id = useId();
return (
<div>
<label htmlFor={id}>{labelText}</label>
<input id={id} type="text" />
{id}
</div>
)
}
export default function Form() {
return (
<form>
<Input labelText={'User Name: '} />
<Input labelText={'User Email: '} />
<Input labelText={'User Password: '} />
</form>
);
}
문제를 해결하기 위해 useId를 사용해서 만들어진 고유한 id를 htmlFor와 id 속성에 넣었습니다.
이젠 다른 label를 눌러도 이어져 있는 옆 input에 정확하게 focus가 잡히게 됩니다.
🍨 참고
https://react.dev/reference/react/useId
useId – React
The library for web and native user interfaces
react.dev
'React > Hooks' 카테고리의 다른 글
useMemo를 알아봅시다. (Feat. 예제) (0) | 2023.04.06 |
---|---|
useReducer로 초초초간단 TodoList 만들기 (6) | 2023.03.23 |
useReducer를 알아보자 (0) | 2023.03.23 |