Problem

How to assign unique ids to form elements? - to be used in form inputs and labels.

 

Solution

Use useId

-----

useId

This is used to generate ids. These unique ids persist between re-renders.

 

----

function Form() {
  const id = useId();

  return (
    <>
      <label htmlFor={id}>First Name</label>
      <input id={id} type="text" placeholder={`Generated id --> ${id}`} />
    </>
  )

}

 

function Form() {
  const idForFirstName = useId();
  const idForLastName = useId();
  const idForEmail = useId();

  return (
    <>
      <label htmlFor={idForFirstName}>First Name</label>
      <input id={idForFirstName} type="text" placeholder={`Generated id --> ${idForFirstName}`} />

      <label htmlFor={idForLastName}>Last Name</label>
      <input id={idForLastName} type="text" placeholder={`Generated id --> ${idForLastName}`} />

      <label htmlFor={idForEmail}>Email</label>
      <input id={idForEmail} type="email" placeholder={`Generated id --> ${idForEmail}`} />
    </>
  )
}

 

// Better use of useId

function Form() {
  const id = useId();

  return (
    <>
      <label htmlFor={`${id}--firstName`}>First Name</label>
      <input id={`${id}--firstName`} type="text" placeholder={`Generated id --> ${id}`} />

      <label htmlFor={`${id}--lastName`}>Last Name</label>
      <input id={`${id}--lastName`} type="text" placeholder={`Generated id --> ${id}`} />

      <label htmlFor={`${id}--email`}>Email</label>
      <input id={`${id}--email`} type="email" placeholder={`Generated id --> ${id}`} />
    </>
  )
}

 

 

// Problem: What if we have many React apps on one page- how do we make sure that there is no overlap of ids.


const sectionA = createRoot(document.getElementById('root1'), {
  identifierPrefix: 'app-sectionA-'
});

sectionA.render(<App />);

const sectionB = createRoot(document.getElementById('root2'), {
  identifierPrefix: 'app-sectionB-'
});

sectionB.render(<App />);