https://react-ko.dev/reference/react/useId accessibility ์์ฑ์ ์ ๋ฌํ ์ ์๋ ๊ณ ์ ID๋ฅผ ์์ฑํ๊ธฐ ์ํ ํ
const id = useId()Returns
- ํน์ ์ปดํฌ๋ํธ ๋ด ํน์
useId์ ๊ด๋ จ๋ ๊ณ ์ ID ๋ฌธ์์ด์ ๋ฐํํ๋ค. ์ด ๊ฐ์ ๋ฆฌ๋ ๋๋ง๋์ด๋ ํญ์ ๋์ผํ๋ค.
Caveats
key๋ฅผ ์์ฑ ํ๊ธฐ์ํด ์ฌ์ฉํ๋ฉด ์๋๋ค.key๋ ๋ฐ์ดํฐ์์ ์์ฑ๋์ด์ผํ๋ค.- ์๋ฒ ๋ ๋๋ง์์ ์๋ฒ์ ํด๋ผ์ด์ธํธ์์ ๋ ๋๋งํ ํธ๋ฆฌ๊ฐ ์ ํํ ์ผ์นํ์ง ์์ผ๋ฉด ์์ฑ๋ ID๊ฐ ์ผ์นํ์ง ์๋๋ค.
์นด์ดํฐ vs useId
์ ์ญ ๋ณ์๋ก nextId++ํ๋ ๊ฒ๋ณด๋ค ์ ๋์๊ฐ?
useId๋ ์๋ฒ๋ ๋๋ง๊ณผ ํจ๊ป ์๋ํ๋ค. ์๋ฒ์ ํด๋ผ์ด์ธํธ์์ ๋ ๋๋งํ ํธ๋ฆฌ๊ฐ ์ ํํ ์ผ์นํ๋ฉด, ๊ฐ์ ์ปดํฌ๋ํธ์ ๊ฐ์ id ๊ฐ์ ์ ๋ฌํ๋ค.- ํด๋ผ์ด์ธํธ ์ปดํฌ๋ํธ๊ฐ hydration ๋๋ ์์๋ ์๋ฒ์ ๋ค๋ฅด๊ธฐ์ ์นด์ดํฐ๋ก๋ ์ด๋ฅผ ๋ณด์ฅํ๊ธฐ๊ฐ ์ด๋ ต๋ค.
Usage
Generating unique IDs for accessibility attributes
import { useId } from 'react';
function PasswordField() {
const passwordHintId = useId();
//...
return (
<>
<input type="password" aria-describedby={passwordHintId} />
<p id={passwordHintId}>
</>
)
}aria-describedBy์ ๊ฐ์ html accessibility ์์ฑ์ผ๋ก ๋ ํ๊ทธ๊ฐ ์๋ก ์ฐ๊ด ๋์ด์์์ ๋ํ๋ผ ์ ์๋ค.
Generating IDs for several related elements
useId๋ ํ์ํ ๋ชจ๋ ์์์ ๋์ํ์ฌ ํธ์ถํ์ง ์์๋ ๋๋ค.
import { useId } from 'react';
export default function Form() {
const id = useId();
return (
<form>
<label htmlFor={id + '-firstName'}>First Name:</label>
<input id={id + '-firstName'} type="text" />
<hr />
<label htmlFor={id + '-lastName'}>Last Name:</label>
<input id={id + '-lastName'} type="text" />
</form>
);
}Specifying a shared prefix for all generated IDs
๋จ์ผ ํ์ด์ง์์ ์ฌ๋ฌ ๊ฐ์ ๋
๋ฆฝ๋ React ์ฑ์ ๋ ๋๋งํ ๋, identifierPrefix ์ต์
์ผ๋ก ๊ณ ์ ํ ์ ๋์ฌ๋ฅผ ๊ฐ ์๋ณ์์ ์ ๋ฌํ ์ ์๋ค
const root1 = createRoot(document.getElementById('root1'), {
identifierPrefix: 'my-first-app-'
});
root1.render(<App />);
const root2 = createRoot(document.getElementById('root2'), {
identifierPrefix: 'my-second-app-'
});
root2.render(<App />);