Skip to content

Commit 8d8c74b

Browse files
authored
Merge pull request #23 from dvkndn/fix-instance-as-result
Support instance-as-result children
2 parents afdd277 + 4425daf commit 8d8c74b

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/__tests__/index.test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,4 +165,36 @@ describe('reactTreeWalker', () => {
165165
expect(actual).toMatchObject(expected)
166166
})
167167
})
168+
169+
it('works with instance-as-result component', () => {
170+
// eslint-disable-next-line react/prefer-stateless-function
171+
class Baz extends Component {
172+
render() {
173+
return (
174+
<div>
175+
<Foo something={1} />
176+
<Foo something={2} />
177+
</div>
178+
)
179+
}
180+
}
181+
const Bar = props => new Baz(props)
182+
const tree = (
183+
<div>
184+
<Bar />
185+
</div>
186+
)
187+
const actual = []
188+
// eslint-disable-next-line no-unused-vars
189+
const visitor = (element, instance, context) => {
190+
if (instance && typeof instance.getSomething === 'function') {
191+
const something = instance.getSomething()
192+
actual.push(something)
193+
}
194+
}
195+
return reactTreeWalker(tree, visitor).then(() => {
196+
const expected = [1, 2]
197+
expect(actual).toEqual(expected)
198+
})
199+
})
168200
})

src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ const pMapSeries = (iterable, iterator) => {
4949
).then(() => ret)
5050
}
5151

52+
const ensureChild = child =>
53+
child && typeof child.render === 'function'
54+
? ensureChild(child.render())
55+
: child
56+
5257
export const isPromise = x => x != null && typeof x.then === 'function'
5358

5459
// Recurse an React Element tree, running visitor on each element.
@@ -68,7 +73,7 @@ export default function reactTreeWalker(
6873
resolve()
6974
}
7075

71-
const child = getChildren()
76+
const child = ensureChild(getChildren())
7277
const theChildContext =
7378
typeof childContext === 'function' ? childContext() : childContext
7479

0 commit comments

Comments
 (0)