-
Notifications
You must be signed in to change notification settings - Fork 2
Assign and reuse element key by child index #1
Conversation
Otherwise changes aren’t reflected until build
One potential issue is that if we try to render a concatenation of two arrays returned by
Minimal proof-of-concept: ReactDOM.render(
[
...nodeListToReact( someNodes, React.createElement ),
...nodeListToReact( someOtherNodes, React.createElement )
],
target
); Not sure what the best solution here would be. Maybe we prefix with an incrementing or another value guaranteed to be unique for each |
Of course they’re matched keys, but that’s not what the test is accomplishing; instead ensure they’re _reused_
To address #1 (comment), 7f62a0c updates logic to assign key as a module-specific prefix combined with a globally incrementing counter, e.g. |
An incrementing counter could be an issue if the number of processed children were to ever exceed @iseulde Do you have any thoughts on these changes? There's a few framework-level changes in the Gutenberg repository related to treating children as array that are blocked by this. |
I'm not sure if I fully understand |
React uses keys in its virtual representation of the DOM, before ever touching the DOM, to help decide what operations needs to be applied. We're working in the opposite direction though. You're right that the idea with applying a key as a property to the node itself is for reuse. Take an example: const listItemNodes = document.querySelector( 'ul' ).childNodes;
const app = document.getElementById( 'app' )
function render() {
ReactDOM.render(
React.createElement(
'ul',
null,
...nodeListToReact( listItemNodes )
),
app
);
}
setInterval( render, 1000 ); Here, if we'd not reused keys on the DOM nodes, React would outright replace the set of rendered list items every single time We'd actually abused this behavior to our advantage in the The above documentation link also references this article which might help clarify a bit more: https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children |
So what if the node did change, but the key is still the same? Will React know that it needs to re-render? Will it detect the changes, even though the key is the same? |
I can try it :) |
Yes, |
Alright, let's merge |
This pull request assigns a key to avoid warnings when the array return value of
nodeListToReact
is rendered as children into a React element. It does so by assigning a key using the index of the child in its parent. Currently this behavior is only applied when usingnodeListToReact
, butnodeToReact
could potentially emulate this by finding its own index within the parent. It also tries to reuse the key by assigning a private-ish property to the DOM node itself. This is in an effort to try to help React reconcile changes more easily, since after all, this is the purpose of thekey
prop in the first place.See: https://facebook.github.io/react/docs/lists-and-keys.html#keys