1

A functional component is implemented like this :

const TestComponent = () => {
   const id1 = React.useId();
   const id2 = React.useId();
   const id3 = React.useId();

   return (
     <div>{ JSON.stringify([ id1, id2, id2 ]) }</div>
   );
}

display this

[ ":Rkm:", ":RkmH1:", ":RkmH2:" ]

These ids seems not valid, why does React return these values?

** EDIT **

According to the official documentation, React.useId() is used to assign id HTML attributes :

function Checkbox() {
  const id = useId();
  return (
    <>
      <label htmlFor={id}>Do you like React?</label>
      <input id={id} type="checkbox" name="react"/>
    </>
  );
};

And, according to the HTML5 specifications, id attributes simply "must contain at least one character" and "must not contain any ASCII whitespace." However, React's documentation also states :

Note

useId generates a string that includes the : token. This helps ensure that the token is unique, but is not supported in CSS selectors or APIs like querySelectorAll.

So, why returning values that aren't compatible with querySelectorAll?

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
  • 1
    Why are these ids not valid to you? These values are all unique - seems good enough to me. – kelsny Nov 03 '22 at 03:26
  • @Evert what is the purpose, then? Because **both** examples on [the official documentation](https://reactjs.org/docs/hooks-reference.html#useid) use it this way!! – Yanick Rochon Nov 03 '22 at 12:08
  • @YanickRochon ah I was wrong. Deleted my comment. Why do you need to use it with QuerySelectAll ? – Evert Nov 03 '22 at 15:36
  • @Evert I simply want to understand why this is so; what good is there that these IDs are simply not unique within their own context, and let users handle the rest? Why making it incompatible with query selectors? As far as my usage is concerned, I typically use these ids are suffixes, like `const id = "form-element-" + React.useId();`, for example. – Yanick Rochon Nov 03 '22 at 15:50

0 Answers0