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 🙏

© 2024 – Pkg Stats / Ryan Hefner

idify-react-component

v1.0.7

Published

Get a ref to a react component by ID

Downloads

12

Readme

Idify React Component

This library provides a utility to create class components from functional components or existing class components, with additional ref management capabilities. This allows you to access and manipulate component instances using IDs.

Installation

npm install idify-react-component

Usage

Creating a Component from a Functional Component

  1. First create your component:

// File: ./MyComponent.tsx
import React, { useImperativeHandle, type ForwardedRef } from 'react';
import { CreateFromFC } from 'idify-react-component';

type PropsType = {};
type RefType = { click: () => void };

function MyComponentFC(props: PropsType, ref: ForwardedRef<RefType>) {
  const onClick = () => {
    // Do something
  };

  // ref object you will get access to later
  useImperativeHandle(ref, () => ({ click: onClick }));

  return <div></div>;
}

const MyComponent = CreateFromFC(MyComponentFC);
export default MyComponent;
  1. Then use it:

// File: ./App.tsx
import React from 'react';
import MyComponent from './src/MyComponent';

function App() {
  const onClick = () => {
    MyComponent.$componentId?.click();
  };

  return <MyComponent id='componentId' />;
}

Notes

  • You can retrieve all mounted components from the refs map, where each entry has a key as the component's ID and the value as the reference. Use MyComponent.refs to access this map

  • Regardless of where the component is rendered, you can obtain a reference to it from anywhere as long as the component is mounted.

  • If you don't pass an id prop, a reference will not be registered in the refs map.

  • Several additional methods will automatically be added to the component reference object: mount, unMount, forceRerender, and getParentName.

  • You can optionally restrict the IDs that can be used and get additional TypeScript types by passing the option ids:

const IDS = ['componentId', 'componentId2'] as const;

// OR

const IDS = {
  forHomePage: 'componentId',
  forDetailPage: 'componentId2',
} as const;

// OR

enum IDS {
  forHomePage = 'componentId',
  forDetailPage = 'componentId2',
}

const MyComponent = CreateFromFC(MyComponentFC, { ids: IDS });
  • Change the the default id prefix $ into something else:
const MyComponent = CreateFromFC(MyComponentFC, { prefix: '' });
MyComponent.$componentId; // default prefix
MyComponent.componentId; // without prefix
  • Change the id prop name to something else:
const MyComponent = CreateFromFC(MyComponentFC, { idPropName: 'refId' });

<MyComponent refId='componentId' />;
  • If you only need TypeScript type checking per component, you can use the setIdType method. This method doesn't change any functionality but adds types to the component:
import MyComponent from './src/MyComponent';

const MyComponentTyped = MyComponent.setIdType<'componentId' | 'componentId2'>();
  • To create from a class component, you can use CreateFromRC:
import ClassComponent from 'some-ui-library';
import { CreateFromRC } from 'idify-react-component';

const MyComponent = CreateFromRC(ClassComponent);

[!WARNING] Components with generic types cannot be inferred by TypeScript correctly. To resolve this, add id to the props type.

type IDs = 'componentId' | 'componentId2'; // or just a string type

// 👇 Add the id type to your props
type PropsType<T> = { id?: IDs; myProp: T };

type RefType = { click: () => void };

function MyComponentFC<T>(props: PropsType<T>, ref: ForwardedRef<RefType>) {
  const onClick = () => {
    // Perform some action
  };

  // ref object you will get access to later
  useImperativeHandle(ref, () => ({ click: onClick }));

  return <div></div>;
}

const MyComponent = CreateFromFC(MyComponentFC);

export default MyComponent;

API

CreateFromFC

Parameters

  • functionComponent (ForwardRefRenderFunction): A React functional component.
  • options

| option | type | | ------------ | --------------------------------------------------------- | | ids | ids?: readonly string[] \| { [K: PropertyKey]: string } | | prefix | prefix?: string | | idPropName | idPropName?: string |

Returns

A class component with the following additional properties:

  • refs (Map): A map of component IDs to their ref objects.
  • setIdType (function): Sets the ID type for TypeScript autocomplete.

CreateFromRC

Parameters

  • ReactClassComponent (ComponentClass): A React class component.
  • options

| option | type | | ------------ | --------------------------------------------------------- | | ids | ids?: readonly string[] \| { [K: PropertyKey]: string } | | prefix | prefix?: string | | idPropName | idPropName?: string |

Returns

A class component with the same additional properties as CreateFromFC.

License

This library is licensed under the MIT License. See the LICENSE file for more information.