-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Description
Describe the problem
There are many cases where an application needs to connect DOM nodes with IDs:
- form fields and labels (
for
) - accessible names (
aria-labelledby
) - more presented here
Given that these IDs do not need any semantic meaning, and given that humans are pretty terrible at coming up with app-level unique IDs, this is a job wonderfully suited for a framework. Taking SSR into consideration, we cannot simply use counter-based solutions or randomly generated IDs.
Describe the proposed solution
React 18 shipped its new useId()
hook which allows utilizing all the component tree knowledge of the framework and using that to generate IDs that are stable across SSR and unique across component instances.
I would like to see a similar thing in Svelte. It could look like this (createInstanceId
):
<!-- sign-in-form.svelte -->
<script lang="ts">
import { createInstanceId } from 'svelte';
const id = createInstanceId();
const usernameID = `${id}-username`;
const passwordID = `${id}-password`;
</script>
<label for={usernameID}>Username</label>
<input id={usernameID} />
<label for={passwordID}>Password</label>
<input id={passwordID} type="password" />
Alternatives considered
Variable
The ID could come from a compiler-populated instance-specific variable:
<label for={$$id}>Username</label>
<input id={$$id} />
Another name could be $$instanceId
, to reflect its instance-dependency. This isn't perfect though, as it still doesn't communicate clearly enough that this isn't a component-specific variable, but rather an instance-specific one. A function call communicates that much better, similarly to createEventDispatcher()
Userland solution
I have used naive ID-generation solutions in the past (namely, lukeed/uid
) and they didn't seem to cause any visible issues, but it's very likely that I simply haven't run into a use-case where a mismatch between the client and the server would be a problem.
Other userland solutions involve contexts, which is not great for developer experience, and might be problematic for asynchronous rendering (see reactwg/react-18#111 (reply in thread))
Importance
would make my life easier