Skip to content

Commit

Permalink
feat: toArray support empty (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed Aug 28, 2020
1 parent 458d5a5 commit 6890680
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Children/toArray.ts
@@ -1,20 +1,25 @@
import React from 'react';
import { isFragment } from 'react-is';

export interface Option {
keepEmpty?: boolean;
}

export default function toArray(
children: React.ReactNode,
option: Option = {},
): React.ReactElement[] {
let ret: React.ReactElement[] = [];

React.Children.forEach(children, (child: any) => {
if (child === undefined || child === null) {
if ((child === undefined || child === null) && !option.keepEmpty) {
return;
}

if (Array.isArray(child)) {
ret = ret.concat(toArray(child));
} else if (isFragment(child) && child.props) {
ret = ret.concat(toArray(child.props.children));
ret = ret.concat(toArray(child.props.children, option));
} else {
ret.push(child);
}
Expand Down
36 changes: 36 additions & 0 deletions tests/toArray.test.js
Expand Up @@ -51,4 +51,40 @@ describe('toArray', () => {
expect(children).toHaveLength(5);
expect(children.map(c => c.key)).toEqual(['1', '2', '3', '4', '5']);
});

it('keep empty', () => {
const wrapper = mount(
<ul>
{null}
<li key="1">1</li>
<>
<li key="2">2</li>
{null}
<li key="3">3</li>
</>
<React.Fragment>
<>
<li key="4">4</li>
{undefined}
<li key="5">5</li>
</>
</React.Fragment>
{undefined}
</ul>,
);

const children = toArray(wrapper.props().children, { keepEmpty: true });
expect(children).toHaveLength(9);
expect(children.map(c => c && c.key)).toEqual([
null,
'1',
'2',
null,
'3',
'4',
null,
'5',
null,
]);
});
});

0 comments on commit 6890680

Please sign in to comment.