Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for function components that return null #924

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,27 @@
expect(findFunctionReturn(def, predicate)).toBeUndefined();
});

test('handles direct prop return', () => {
const def = parse.statement(`
function Foo ({ children }) {
return children;
}
`);

expect(findFunctionReturn(def, predicate)).toBeDefined();
});

test('handles null return', () => {
const def = parse.statement(`
function Foo (props) {
return null;
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What worries me is that literaly any function that returns null will be detected as react component.
Same for the other usecase.

`);

const received = findFunctionReturn(def, predicate);
expect(received).toBeDefined();

Check failure on line 173 in packages/react-docgen/src/utils/__tests__/findFunctionReturn-test.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected blank line before this statement
});

testReturnValues(
'does not see ifs as separate block',
`
Expand Down
10 changes: 9 additions & 1 deletion packages/react-docgen/src/utils/findFunctionReturn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ const explodedVisitors = visitors.explode<TraverseState>({
enter: function (path, state) {
const argument = path.get('argument');

if (argument.hasNode()) {
if (argument.node?.type === 'NullLiteral') {
// Handle null return value
state.resolvedReturnPath = path;
path.stop();
} else if (argument.hasNode()) {
const resolvedPath = resolvesToFinalValue(
argument,
state.predicate,
Expand Down Expand Up @@ -90,6 +94,10 @@ function resolvesToFinalValue<T extends NodePath>(
}
}

if (resolvedPath.isObjectProperty()) {
return resolvedPath as T;
}

return;
}

Expand Down
Loading