Repository navigation
Description
Howdy ya'll,
tl dr: please provide a way to coordinate pseudo-random identifiers across the client and server
This issue has been discussed a bit before (#1137, #4000) but I continually run into this issue, trying to build libraries that provide accessible components by default. The react component model generally speaking offers a big opportunity to raise the often low bar for accessibility in the library and widget world, see experiments like @ryanflorence's react-a11y.
For better or for worse the aria, and a11y API's in the browser are heavily based on using ID's to link components together. aria-labelledby, aria-describedby, aria-owns,aria-activedescendent, and so on all need's ID's. In a different world we would just generate ids where needed and move on, however server-side rendering makes that complicated, because any generated ID is going to cause a mismatch between client/server.
We've tried a few different approaches to address some of this, one is making id's required props on components that need them. That gets kinda ugly in components that need a few id's but moreso it annoys users. Its unfortunate because if we could generate deterministic id's we could just provide more accessible components by default.
The frustrating part is that the component generally has all the information it needs to just set the various aria info necessary to make the component usable with a screen reader, but are stymied by not having the user provide a bunch of globally unique ids'
So far only really reasonable approaches I've seen are @syranide's solution of a root ID store, and using _rootID. The latter obviously has problems. The former doesn't scale well for library authors. Everyones' root App component is already wrapped in a Router, Provider, etc, having every library use their own root level ID provider is probably not super feasible and annoying to users.
It seems like the best way to do this would be if React (or a React addon) could just provide a consistent first class way to get a unique identifier for a component, even if it is just a base64 of the node's _rootID.
thanks for all the hard work everyone!
Activity
milesj commentedon Jan 16, 2016
I currently solve this by generating a UID in a components constructor, which is then used as the basis for all my DOM IDs -- as seen here: https://github.com/titon/toolkit/blob/3.0/src/Component.js#L115
I then pass this UID along to all the children via contexts, which allows them to stay consistent: https://github.com/titon/toolkit/blob/3.0/src/components/accordion/Header.js#L62 I would then end up with IDs like
titon-s7h1nks-accordion-header-1andtiton-s7h1nks-accordion-section-1.IMO, this kind of functionality doesn't really need to be part of React.
jquense commentedon Jan 16, 2016
I think your solution still suffers from the exact problem I'm talking about here. Your code seems to depend on this
generateUIDfunction which would break server rendering, since the uid generated on the server, is not going to be the one generated on the client, random numbers and all.rileyjshaw commentedon Jan 17, 2016
Pulling from #4000, which is a bit long... I believe the major criteria were:
.addons)idsFrom #1137,
Seems it's gotten a bit beyond that now :)
milesj commentedon Jan 17, 2016
@jquense Then simply write a UID generator function that returns the same value on the server or the client.
jquense commentedon Jan 17, 2016
@milesj thanks for the suggestions tho in this case that is only helpful if you have one instance of a component on the page.
@rileyjshaw I think that sums up the issue very succinctly, thank you. The best solution is the root store that passes ID's via context, but that's a bit cumbersome for each library to invent and provide unless there was some consensus in the community.
milesj commentedon Jan 17, 2016
You're over-thinking this a bit. All the reasons you keep stating are easily fixable. Assuming that the server and client render everything in the same order (not sure why they wouldn't), just have a separate function module that generates and keeps track of things.
And in the component.
And if for some reason you want individually incrementing counters per component, then just use a
WeakMapin the function module.jquense commentedon Jan 17, 2016
@milesj I appreciate your suggestions and efforts at a solution but you may not be familiar enough with the problem. The simple incrementing counter doesn't work, if only because ppl don't usually render exactly the same thing on the client and server. I think you might want to read the linked issues, specifically #4000. I am well aware of the issues and the possible solutions, if there was an simple straightforward solution that worked I wouldn't be here.
jimfb commentedon Jan 17, 2016
I think @jquense makes a valid point about us needing a good solution here - it is currently overly painful to coordinate psudorandom identifiers for component. The problem is exacerbated when different components choose different solutions for solving the coordination problem. We see the exact same problem when components use the clock (for instance, to print relative times). We also see similar use cases for things like sharing flux stores across component libraries. Anyway, I think it would be good to find a real/supported solution for this use case.
brigand commentedon Jan 17, 2016
What about
React.getUniqueId(this)which makes an id based on the key path + an incrementing counter for that key path. ReactDOMServer.renderToString could reset the hash of paths to counter ids.cannona commentedon Feb 1, 2016
Sorry if this comment is ignorant. I'm a bit of a noob, but if the key path is always unique and immutable, would we need a counter at all? So, in short:
React.getUniqueId(this[, localId])
This would return a unique id based on the key path, and the optional second argument, if provided. The function would be pure, in that it would always return the same output given the same inputs, I.E. no counter.
If more than one ID was needed within the same component, the optional second argument could be provided to differentiate between the two.
Of course if key paths aren't immutible and unique, then this obviously won't work.
jquense commentedon Apr 11, 2016
@jimfb did you, or the rest of ya'll at FB have any thoughts about a potential API for this sort thing?
I might be able to PR something but not quite sure what everyone thinks the reach should be. Coordinating identifiers is a different sort of thing that coordinating a some sort of server/client cache, which is what suggests itself to me thinking about the Date or flux store use-case.
bjornstar commentedon Feb 24, 2017
Here's what I did:
in my components I just
I agree that it would be nice if react provided a standard way of syncing values between client and server. That being said, I don't know what the API would look like and this was pretty easy to do.
n8mellis commentedon Feb 28, 2017
I hacked up something recently that seems to do the trick. I noticed that when rendered server-side, the DOM nodes will all have the
data-reactidattribute set on them. So myuniqueIdForComponentfunction will first check the rendered DOM node to see if that attribute is set. If it is, it will simply return that. If not, then it means we weren't rendered server-side and don't have to worry about keeping them in sync so we can just use an auto-increment approach suggested before. Code looks something like this:There is undoubtedly a more optimized way to do this, but from recent observation, the methodology appears to be sound; at least for my usage.
PaulKiddle commentedon Jun 5, 2017
@n8mellis Unfortunately
findDOMNodewill throw if called during or before the first client-side render.[-]A11y: generating unique ID's and SSR[/-][+]Generating unique ID's and SSR (for a11y and more)[/+]15 remaining items
up209d commentedon Apr 27, 2018
I did it with Redux Store: could be a
middlewareor just a function instore stateuid.jsStore GeneratoruidAction.js
Somewhere in Component with connect
By doing this,
Client StoreandServer Storein every request will have samecounteroutcome when is called. Using Reduxconnectwe can access to this action everywhere.Merri commentedon Jun 5, 2018
See theKashey comment below.
theKashey commentedon Feb 5, 2019
It's a bit strange to read such long conversation, when @milesj described the "right" solution years ago:
prefix=youPrefix+youIdto your child and reset counter. So repeat the .1, with a "longer" prefix.https://github.com/thearnica/react-uid is implementing all there features, while
maria-uidis bound to the render order of the components, which depends on code-splitting, the order data got loaded, a moon phase and so on.up209d commentedon Feb 5, 2019
@theKashey that's because everyone wanted to note their idea to remind the community and themselves, just like you and me so the topic is long. This unique UID with SSR friendly is just a simple trick but worth for noting down.
Drop generateId support
Drop generateId support
shpindler commentedon Aug 21, 2020
I've tried to store id counter in the local scope of the component but it seems won't work too:
gaearon commentedon Aug 21, 2020
Just to follow up on this, we are testing a potential solution to this internally but not ready to draft an RFC yet.
yarastqt commentedon Sep 14, 2020
Im wrote hook for generate ID with SSR supports. Gist with example — https://gist.github.com/yarastqt/a35261d77d723d14f6d1945dd8130b94
Merri commentedon Sep 14, 2020
@yarastqt There are issues your solution does not cover (it never resets the SSR counter for example), see react-uid instead.
yarastqt commentedon Sep 14, 2020
@Merri it's not true, i increase counter only on client side
nemoDreamer commentedon May 22, 2021
Tangential to this thread, if anyone is interested, I wrote a lil' context/hook that returns an RNG seeded by the value you pass into its provider, and it's served me well in keeping random values between server and client:
In your parent component:
Then, in your nested components:
Hope it's useful to someone! 😄
phegman commentedon Feb 28, 2022
I am using
@reach/auto-idand it seems to be working well out of the box for me!eps1lon commentedon Mar 5, 2022
There are plans currently to ship
useIdin React 18 which should resolve this request. If there's anything missing please continue the discussion in reactjs/rfcs#32gaearon commentedon Mar 29, 2022
useId()is out in React 18.https://reactjs.org/blog/2022/03/29/react-v18.html#useid