Unique component identifier
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?
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.
@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.
@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.
@syranide I mean if you have two composite components nested with no DOM node in between then they share a rootNodeID:
https://github.com/facebook/react/blob/95edc396dfd07ed064240b5e2e1a1d5528d2d747/src/core/ReactCompositeComponent.js#L839-L843
@spicyj Ah right, right, _rootNodeID emphasis on Node as in DOMNode. Excellent point, they're only unique in the DOM (loosely speaking).
@spicyj Can close this (this was solved on IRC btw).
@syranide @spicyj - For those of us who weren't on IRC - what was the resolution?
@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.
@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
@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.)
@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();
}
}
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>
);
}
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?
@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.
I thought that might be the case, but I've got 49 components and a few hundred instances nested up to 6-7 levels deep which I would consider non-trivial.
And it works fine.
Is there a specific scenario that comes to mind where the initial client-side markup rendered by ReactDom.render() won't match the markup generated by ReactDOMServer.renderToString()?
(Webpack's hot swapping will make them out of sync but I don't care about that.)
React 15 has nulled many _rootNodeId, any other ideas? Generating ids isn't a good solution for us, since we need a unique id for 3rd party components as well, and wrapping a 3rd party components is something we want to avoid.
You could use a WeakMap and store an ID for each instance. _rootNodeID was never public API and we no longer needed a unique ID on composite components so we got rid of it. Depending on your use case, perhaps you can refactor your API so that the third-party components are wrapped and your wrapper can generate an ID.
@spicyj We are trying to make redux-devtools' time travelling feature to actually replay inner component states. So our use case, is being able to inject a state object into a component, only by ID, since instances get created/disposed during the time travel. So bottom line, our map consists of comoponentID -> componentState, and we use ID to locate the current component instance. This worked for us, until React 15 (we used some internals though).
We were also relying on _rootNodeID as an identifier to cache component state on componentWillUnmount, so that we can restore it for all components when the user presses the back button, on componentWillMount.
This is an important use case for us and this ID was a perfect fit. We knew we were taking a risk using internals, but still... is there any reliable alternative? We thought about generating some kind of component xpath by traversing the hierarchy, but it doesn't seem very performant to do for several components.
@ricardosoeiro The approach you describe is very fragile and not really supported. Have you looked into using something like Flux or Redux instead? They support exactly this use case, but in a different and more explicit way.