Skip to content

Unique component identifier #1137

Closed
Closed

Description

@andreypopp

Both react-async and react-multiplayer need components to have unique identifiers.

In case of react-async — to maintain a mapping from a component to its state and make it serialisable (to send it over the wire, ES6 Map with components as keys can't be used), in case of react-multiplayer — to have an unique URL per component instance.

Currently both of the libraries use this._rootNodeID + ',' + this._mountDepth. Should this be added to a public API — getComponentID() or something?

Activity

  1. syranide commented on Feb 20, 2014

    @syranide
    Contributor

    this._rootNodeID + ',' + this._mountDepth is redundant even, this._rootNodeID is enough. However, the unique ID is an implementation detail AFAIK, it's likely that it will be removed in the future if/when we ever let go of innerHTML. Also, it's possible that a concatenated ID won't be available soon, but each node will only hold it's own relative ID and possibly a monotonic unique ID for innerHTML (again, implementation detail).

    Also this._rootNodeID is only unique at a single point in time, it's not unique over time. I'm unsure why this can't be solved for example via a Mixin that creates a unique ID for the component by just incrementing a global counter.

  2. sophiebits commented on Feb 20, 2014

    @sophiebits
    Collaborator

    @syranide _rootNodeID can be shared by multiple composite components, correct?

    This seems like something that's fragile -- for cases where you only need a unique ID on one client but don't need it to be consistent across clients, you can make your own autoincrementing counter. For cases where you want the IDs to be consistent across clients, I don't think you can rely on this._rootNodeID because rendering components in a different order (or with server rendering, on different servers) will cause the node IDs to be different -- when you need this I think you really just want to force the person using a mixin to specify a unique key.

  3. syranide commented on Feb 20, 2014

    @syranide
    Contributor

    @spicyj _rootNodeID must be unique at any point in time, but it only describes the hiearchy of indices and keys, so once a component is removed, the _rootNodeID is likely to be immediately assumed by another component taking it's place.

    Anyway, @andreypopp messages me in the chat and it seemed like the Mixin approach was a good solution.

  4. sophiebits commented on Feb 20, 2014

    @sophiebits
    Collaborator
  5. syranide commented on Feb 20, 2014

    @syranide
    Contributor

    @spicyj Ah right, right, _rootNodeID emphasis on Node as in DOMNode. Excellent point, they're only unique in the DOM (loosely speaking).

  6. syranide commented on May 18, 2014

    @syranide
    Contributor

    @spicyj Can close this (this was solved on IRC btw).

  7. laser commented on Apr 23, 2015

    @laser

    @syranide @spicyj - For those of us who weren't on IRC - what was the resolution?

  8. syranide commented on Apr 23, 2015

    @syranide
    Contributor

    @laser IIRC simply that it was there were better ways to approach the problem that doesn't rely on internals. I have a faint memory of him simply generating a unique ID for each component on mount and using that instead, but I could be way off.

  9. laser commented on Apr 23, 2015

    @laser

    @syranide Ah, okay. Thanks for clarifying.

    My team is trying to come up with an approach for including a view-specific token with our actions such that errors (say, failing server-side validation) can be linked back to originating views w/out introducing granular, view-specific stores. The approach was suggested by @jingc here. I'd love to be able to rely on a unique id set by React instead of having to generate something myself, if possible.

    Take care,

    Erin

  10. sophiebits commented on Apr 23, 2015

    @sophiebits
    Collaborator

    @laser Yeah, if all you need is a unique ID for each component then you can make a counter yourself and increment it for each new component. (We try to avoid adding functionality to React if it can be easily replicated in component code.)

  11. laser commented on Apr 23, 2015

    @laser

    @spicyj Cool, makes sense.

    Without thinking too hard about it, I could imagine something like:

    class BaseComponent extends React.Component {
      constructor(props) {
        super(props);
        this.componentId = SomeLib.createComponentId();
      }
    }
    
  12. lemiii commented on May 8, 2015

    @lemiii

    I don't necessarily like what i'm doing since it's hacky and has a chance of collisions when you have multiple instances on the same page, but I set the state of the component with a random id, and then use that.

    getInitalState: function() {
      return { 
        id: Math.floor(Math.random() * 0xFFFF) 
      }
    },
    
    getId: function(name) {
      return name + this.state.id;
    },
    
    render: function() {
      return (
        <div>
          <input type="checkbox" id={this.id('agreeCheckbox')} />
          <label htmlFor={this.id('agreeCheckbox')}>I agree</label>
        </div>
      );
    }
  13. davidgilbertson commented on Nov 18, 2015

    @davidgilbertson
    Contributor

    A simple counter and component-specific string works just fine for me.

    import React, {Component} from 'react';
    
    let count = 0;
    
    class InputUi extends Component {
        constructor(props) {
            super(props);
    
            this.guid = 'input-ui-' + count++;
        }
    
        render() {
            return (
                <span>
                    <label htmlFor={this.guid}>
                        {this.props.label}
                    </label>
    
                    <input
                        id={this.guid}
                        />
                </span>
            );
        }
    }
    
    export default InputUi;

    Is there a scenario where this won't work?

  14. syranide commented on Nov 18, 2015

    @syranide
    Contributor

    @davidgilbertson Server-rendering, it will work in some trivial setups but for everything beyond that will cause count to become out-of-sync between client and server and cause markup mismatch.

  15. 22 remaining items

  16. klaygomes commented on Mar 16, 2017

    @klaygomes

    3 years and nothing yet? What a shame!

  17. jpfiorilla commented on Jun 30, 2017

    @jpfiorilla

    I used this._reactInternalInstance._debugID for unique classNames for a fancy scrollmagic/gsap effect and when i deployed the whole site shat itself lol

  18. OutThisLife commented on Jul 7, 2017

    @OutThisLife

    +1

  19. sfrieson commented on Jul 12, 2017

    @sfrieson
    Contributor

    I have a solution that's working pretty well so far. I've been generating sequential ids with a simple utility, and living with the checksums for the time being. This is inspired by what @jwietelmann said above about resetting on a per-request basis but is maybe worth saying again. As he said, this not as much help if you're working on a component library, but works best when you're creating the entire app.

    // utility to generate ids
    let current = 0
    
    export default function generateId (prefix) {
      return `${prefix || 'id'}-${current++}`
    }
    
    export function resetIdCounter () { current = 0 }
    

    And then in a root component I call the resetCounter function. On the server, this clears the id from memory each time there's a new server render. In the browser, it doesn't really reset anything, but that's fine.

    Working well so far.

  20. mtrabelsi commented on Sep 8, 2017

    @mtrabelsi

    Actually it's not that complicated to get a unique ID:

      
    constructor(props) {
          super(props);
          this.id = new Date().getTime();
      }
    

    As for CSS selector needs the first letter to be a character you can prefix it with an 'id-' on the render method :

      render() {
          return (<div id={`id-${this.id}`}>
                               ...
                  </div>);
      }
    

    Works like a charm, don't wait for React - they have their own policy and list of future pending , maybe will never be implemented :)

  21. nhunzaker commented on Sep 8, 2017

    @nhunzaker
    Contributor

    @mtrabelsi That approach is dangerous because multiple components may be created in under a millisecond. The time resolution isn't high enough.

    Still, the technique of assigning ids in the constructor is how I've approached this in the past. However I've used a uuid library for it, and usually prepend a prefix to make the id contextual:

    constructor(props) {
        super(props);
        this.id = "thing-" + uuid()
    }

    This isn't perfect, and I still like to generate an ID based on props when I can, but it accomplishes the task if prop-based identifiers fail.

  22. jquense commented on Sep 8, 2017

    @jquense
    Contributor

    uuid's in constructors work fine if you don't need SSR, other tho it's likely the id's will mismatch between server and client :/

  23. omerts commented on Sep 8, 2017

    @omerts

    @mtabelsi @nhunzaker, both solutions will not create a persistent id, especially if a certain component is mounted/unmounted across renders (even moving between tabs might unmount a component), not to say between refreshes.

  24. nhunzaker commented on Sep 8, 2017

    @nhunzaker
    Contributor

    @omerts Correct. It definitely does not fix the issue.

    I think this could be a really great feature. Unfortunately I don't really understand enough about Fiber to make it happen, but would happily assist anyone trying to figure this out.

  25. sophiebits commented on Sep 8, 2017

    @sophiebits
    Collaborator

    We should probably agree on whether we want this and how it should behave before considering implementations (unless it's just for a proof of concept).

  26. nhunzaker commented on Sep 8, 2017

    @nhunzaker
    Contributor

    @sophiebits Ah sorry, I shouldn't get ahead of myself! I'd love to figure out some resolution here.

  27. sebmarkbage commented on Sep 9, 2017

    @sebmarkbage
    Contributor

    This issue isn't about IDs. It's about whether it's a good idea to preserve state across serialization and if the use cases for that in turn can't be modeled better. Don't get stuck on the ID thing. If serialization is a good idea maybe it's better we just build that in.

  28. vorillaz commented on Apr 1, 2018

    @vorillaz

    I prefer using HOCs where needed in order to easily manipulate nested components.

    import React from 'react';
    let idx = 0;
    const uuid = () => idx++;
    
    export default Wrapped => props => {
      const { id, ...rest } = props;
      const uniqueId = id ? id : `id-${uuid()}`;
      return <Wrapped {...rest} id={uniqueId} />;
    };
  29. ruucm commented on Jul 2, 2018

    @ruucm

    For 2 Days research, I got a solution for this headache problem.

    Here is my solution

    Make Unique Id by props in React

  30. Exifers commented on Jul 3, 2022

    @Exifers

    Here is a POC, but unfortunately if this hook is called multiple times in the same component, it gives different ids.

    let id = 0;
    
    const useMountId = () => {
      const ref = useRef<string>();
      
      if (!ref.current) {
        ref.current = (++id).toString(10);
      }
    
      return ref.current;  
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions