npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-cmp-selector

v2.0.1

Published

A powerful and extensible utility for filtering and selecting React components based on specified attributes and values.

Readme

react-cmp-selector

A powerful and extensible utility for selecting and manipulating React components based on attributes. Ideal for dynamic layouts, slotted rendering, and component injection patterns.


Table of Contents


Installation

npm install react-cmp-selector

or using yarn:

yarn add react-cmp-selector

Motivation

React does not support named slots or dynamic selection of children out of the box. This utility solves that by providing:

  • A hook to search through children by attribute
  • A component-based API (<Slot>) for declarative slot usage
  • Tools to inject props, merge handlers, and validate layout contracts

Table of Proposals

| Feature | Prop / Option | Type | Description | | ----------------------------- | -------------------------- | --------------------------------- | ------------------------------------------------------------- | | Attribute Matching | attribute | string | Attribute name to search for (default: 'data-slot') | | Value Matching | value / name | string | The value to match against the selected attribute | | Prop Merging | props | Partial<P> | Injected props to merge into the matched component(s) | | Function Merging Strategy | functionPropMerge | 'combine' \| 'override' | Defines how function props like onClick should be merged | | Debug Mode | debug | boolean | Enables logging of matching and merging behavior | | Match All | findAll | boolean | If true, returns all matching components instead of the first | | Hook Interface | getCmpByAttr() | — | Programmatic interface to extract and modify children | | Declarative API | <Slot> | — | React component alternative to the hook | | Slot Markers | SlotUtils.createMarker() | — | Creates a named slot wrapper component | | Slot Validation | SlotUtils.validate() | — | Dev-only validation for required slot presence | | Fallback Rendering | fallback | ReactNode | Rendered if no matching slot is found | | onFound Callback | onFound | (element: ReactElement) => void | Runs when a match is found (e.g. for side effects) |


Usage

1. Basic Slot Matching

Children

export function ChildComponents() {
  return (
    <>
      <div data-slot="header">Header</div>
      <div data-slot="body">Body</div>
      <div data-slot="footer">Footer</div>
    </>
  );
}

Parent

const header = getCmpByAttr({
  children: <ChildComponents />,
  value: "header",
  props: { className: "highlighted" },
});

Output

<div data-slot="header" class="highlighted">Header</div>

How It Works

  • getCmpByAttr() searches children for data-slot="header".
  • The match is cloned with the className prop added.

2. Matching Multiple Components

Children

function Buttons() {
  return (
    <>
      <button data-role="action-button">Save</button>
      <button data-role="action-button">Cancel</button>
    </>
  );
}

Parent

const buttons = getCmpByAttr({
  children: <Buttons />,
  attribute: "data-role",
  value: "action-button",
  findAll: true,
  props: { "data-tracked": true },
});

Output

<button data-role="action-button" data-tracked="true">Save</button>
<button data-role="action-button" data-tracked="true">Cancel</button>

3. Combining Event Handlers

Children

function CTA() {
  return (
    <button data-slot="cta" onClick={() => console.log("child")}>
      Click Me
    </button>
  );
}

Parent

const cta = getCmpByAttr({
  children: <CTA />,
  value: "cta",
  props: {
    onClick: () => console.log("parent"),
  },
  functionPropMerge: "combine",
});

Behavior

Console logs:

child
parent

4. Declarative API with <Slot>

export function Layout({ children }: { children: React.ReactNode }) {
  return (
    <div>
      <Slot name="header">{children}</Slot>
      <main>
        <Slot name="content">{children}</Slot>
      </main>
    </div>
  );
}
function PageContent() {
  return (
    <>
      <div data-slot="header">Welcome</div>
      <div data-slot="content">Hello, world!</div>
    </>
  );
}

<Layout>
  <PageContent />
</Layout>;

Output

<div>
  <div data-slot="header">Welcome</div>
  <main>
    <div data-slot="content">Hello, world!</div>
  </main>
</div>

5. Fallback Slot Content

<Slot name="hero" fallback={<div>Default Hero</div>}>
  {children}
</Slot>

If no data-slot="hero" is found, it renders:

<div>Default Hero</div>

6. Slot Markers

Marker Declaration

const HeroSlot = SlotUtils.createMarker("hero");

function Page() {
  return (
    <HeroSlot>
      <div className="hero-banner">Custom Hero</div>
    </HeroSlot>
  );
}

Parent

<Slot name="hero" fallback={<div>Default Hero</div>}>
  <Page />
</Slot>

7. Slot Validation

SlotUtils.validate(children, ["header", "footer"]);
  • Dev-only.
  • Warns if data-slot="header" or footer is missing in children.

Use Cases

  • Composable Layouts: Dynamically slot content into shared layouts.
  • Design Systems: Enable flexible API layers with predictable slot names.
  • Multi-brand / White-label UIs: Inject branding-specific content without hardcoding.
  • Next.js Layouts: Use context + slots to bridge app/layout.tsx and pages.
  • Dynamic Prop Injection: Apply analytics, A/B testing, or class injection to specific slots.

API Reference

getCmpByAttr<P>()

function getCmpByAttr<P>(
  options: ComponentFinderProps<P>
): ReactNode | ReactNode[] | null;

ComponentFinderProps

interface ComponentFinderProps<P = unknown> {
  children: ReactNode;
  attribute?: string;
  value?: string;
  props?: Partial<P>;
  debug?: boolean;
  findAll?: boolean;
  onFound?: (component: ReactElement) => void;
  functionPropMerge?: "combine" | "override";
}

Slot

<Slot
  name="footer"
  props={{ className: "sticky" }}
  fallback={<DefaultFooter />}
>
  {children}
</Slot>

SlotUtils

SlotUtils.createMarker(name: string, attribute?: string): Component
SlotUtils.validate(children: ReactNode, requiredSlots: string[], attribute?: string): void

Caveats

  • Next.js layouts require a shared context if crossing page boundaries.
  • getCmpByAttr only works on elements rendered within the same render cycle.
  • This is not a DOM query tool – it’s entirely based on React element trees.

License

MIT License