Skip to content
This repository has been archived by the owner on Jan 19, 2021. It is now read-only.

Commit

Permalink
Assign key by prefixed global counter
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed May 5, 2017
1 parent cc3d198 commit 7f62a0c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,12 @@ export function attributeListToReact (attributeList) {
}, {})
}

let keyCounter = 0

export function nodeListToReact (nodeList, createElement) {
return [...nodeList].reduce((accumulator, node, index) => {
return [...nodeList].reduce((accumulator, node) => {
if (!node._domReactKey) {
node._domReactKey = String(index)
node._domReactKey = '_domReact' + String(keyCounter++)
}

const child = nodeToReact(node, createElement)
Expand Down
17 changes: 11 additions & 6 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it } from 'mocha'
import { equal } from 'assert'
import { equal, ok } from 'assert'
import { JSDOM } from 'jsdom'
import { createElement } from 'react'
import { renderToStaticMarkup } from 'react-dom/server'
Expand Down Expand Up @@ -97,14 +97,19 @@ describe('nodeToReact()', () => {
})

describe('nodeListToReact', () => {
const rxKey = /^_domReact\d+$/
function assertKey (key) {
ok(rxKey.test(key), 'expected to match key pattern ' + rxKey.toString())
}

it('should return array of React element with key assigned by child index', () => {
document.body.innerHTML = '<p>test <span>test</span></p><strong>test</strong>'
const elements = nodeListToReact(document.body.childNodes, createElement)

equal('0', elements[0].key)
assertKey(elements[0].key)
equal('string', typeof elements[0].props.children[0])
equal('1', elements[0].props.children[1].key)
equal('1', elements[1].key)
assertKey(elements[0].props.children[1].key)
assertKey(elements[1].key)
})

it('should reuse assigned key for same elements reference', () => {
Expand All @@ -116,8 +121,8 @@ describe('nodeToReact()', () => {
list.insertBefore(list.lastChild, list.firstChild)

elements = nodeListToReact(list.childNodes, createElement)
equal('1', elements[0].key)
equal('0', elements[1].key)
assertKey(elements[0].key)
assertKey(elements[1].key)
})
})
})

0 comments on commit 7f62a0c

Please sign in to comment.