Skip to content
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
@@ -0,0 +1,38 @@
import React from "react";
import isIconOnly from "./is-icon-only";

const TestIcon = () => <span>I am an Icon</span>;
TestIcon.displayName = "Icon";

describe("isIconOnly", () => {
it("should return true when only icon is provided", () => {
expect(isIconOnly(<TestIcon />)).toBe(true);
});

it("should return false when children text is provided", () => {
expect(isIconOnly("Click me")).toBe(false);
});

it("should return false when children number is provided", () => {
expect(isIconOnly(42)).toBe(false);
});

it("should return false when children with no icon is provided", () => {
expect(isIconOnly(<span>I am no Icon</span>)).toBe(false);
});

it("should return false when both icon and text are provided", () => {
expect(
isIconOnly(
<>
<TestIcon />
Click me
</>,
),
).toBe(false);
});

it("should return false when no children are provided", () => {
expect(isIconOnly(undefined)).toBe(false);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { ReactNode, Children, isValidElement, FunctionComponent } from "react";
import { isFragment } from "react-is";

const isIconOnly = (children: ReactNode): boolean => {
if (!children) return false;

const childArray = Children.toArray(children);

return childArray.every((child) => {
// Check if it's a React element
if (!isValidElement(child)) {
// If it's a string, check if it's only whitespace
if (typeof child === "string") {
return !child.trim().length;
}
// Numbers, booleans etc
return false;
}

// Check if it's an Icon component
if ((child.type as FunctionComponent).displayName === "Icon") {
return true;
}

// Check if it's a Fragment with nested children
if (isFragment(child)) {
return isIconOnly(child.props.children);
}

// Any other element counts as content
return false;
});
};

export default isIconOnly;
Loading
Loading