Skip to content

Commit

Permalink
Support instance-as-result children
Browse files Browse the repository at this point in the history
  • Loading branch information
Thien Do committed Mar 12, 2018
1 parent 5951226 commit 4425daf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
32 changes: 32 additions & 0 deletions src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,36 @@ describe('reactTreeWalker', () => {
expect(actual).toMatchObject(expected)
})
})

it('works with instance-as-result component', () => {
// eslint-disable-next-line react/prefer-stateless-function
class Baz extends Component {
render() {
return (
<div>
<Foo something={1} />
<Foo something={2} />
</div>
)
}
}
const Bar = props => new Baz(props)
const tree = (
<div>
<Bar />
</div>
)
const actual = []
// eslint-disable-next-line no-unused-vars
const visitor = (element, instance, context) => {
if (instance && typeof instance.getSomething === 'function') {
const something = instance.getSomething()
actual.push(something)
}
}
return reactTreeWalker(tree, visitor).then(() => {
const expected = [1, 2]
expect(actual).toEqual(expected)
})
})
})
7 changes: 6 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ const pMapSeries = (iterable, iterator) => {
).then(() => ret)
}

const ensureChild = child =>
child && typeof child.render === 'function'
? ensureChild(child.render())
: child

export const isPromise = x => x != null && typeof x.then === 'function'

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

const child = getChildren()
const child = ensureChild(getChildren())
const theChildContext =
typeof childContext === 'function' ? childContext() : childContext

Expand Down

0 comments on commit 4425daf

Please sign in to comment.