Registry / web-framework / react-multi-ref

react-multi-ref

JSON →
library1.0.2jsnpmunverified

react-multi-ref is a lightweight utility library designed to simplify managing references to multiple, dynamically created React elements. It addresses a common challenge in React development where developers need to collect and interact with a collection of DOM nodes or component instances, especially when dealing with lists or forms. The current stable version is 1.0.2, indicating a mature and stable API. As a utility, its release cadence is likely slow, focusing on stability rather than frequent feature additions. Key differentiators include its simplicity, providing a `Map`-like interface to access refs by a custom key, and its explicit support for both functional components (via `useState`) and class components, with integrated TypeScript and Flow type definitions for enhanced developer experience. It avoids the complexities of managing arrays of refs manually or relying on less explicit methods.

npm install react-multi-ref
INSTALL
IMPORT
SIG · REACT-MULTI-REF
R
react-multi-ref
web-frameworkjavascriptv1.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

MultiRef
import MultiRef from 'react-multi-ref';
const MultiRef = require('react-multi-ref').MultiRef;
This package uses a default export for the MultiRef class. For CommonJS, `require('react-multi-ref')` directly returns the class.
MultiRef instance
const [itemRefs] = useState(() => new MultiRef());
const itemRefs = useMemo(() => new MultiRef(), []);
When using in function components, create the MultiRef instance using `useState` with a factory function to ensure it persists across renders and avoids React's potential memory resets, unlike `useMemo`.
ref callback
<input ref={itemRefs.ref(i)} />
<input ref={itemRefs.ref} />
The `ref` method requires a unique key parameter to associate the DOM element with that key in the internal map.

Demonstrates how to use MultiRef in a functional React component to manage references to multiple dynamically created input elements and retrieve their values.

import { useState } from 'react'; import MultiRef from 'react-multi-ref'; function MyDynamicForm() { // Initialize MultiRef using useState to persist the instance across renders const [inputRefs] = useState(() => new MultiRef()); // Generate 5 input fields, assigning a ref to each using its index as a key const inputElements = new Array(5).fill(null).map((_, i) => ( <div key={i} style={{ marginBottom: '10px' }}> <label> Input {i + 1}: <input type="text" ref={inputRefs.ref(i)} placeholder={`Value for item ${i + 1}`} /> </label> </div> )); // Event handler to collect all input values function handleSubmit() { const values = []; inputRefs.map.forEach((inputElement, key) => { if (inputElement) { values.push(`Key ${key}: ${inputElement.value}`); } }); alert("Current input values:\n" + values.join('\n')); } return ( <div> <h3>Dynamic Input Form</h3> {inputElements} <button onClick={handleSubmit} style={{ marginTop: '20px', padding: '10px 15px' }}> Get All Input Values </button> </div> ); } // To run this example in a React application: // export default MyDynamicForm;
Debug
Known issues
gotchaWhen using `react-multi-ref` in functional components, the `MultiRef` instance must be created and persisted using `useState` (e.g., `useState(() => new MultiRef())`). Do not use `useMemo` for this purpose, as React is allowed to reset memoized values at any time, which would lead to loss of ref tracking.
fix
Always initialize `MultiRef` inside `useState`'s factory function: `const [myRefs] = useState(() => new MultiRef());`
affects: >=1.0.0
gotchaEach call to `multiRef.ref(key)` requires a unique `key` parameter. This key is used to identify and retrieve the specific element from the internal `Map`. Reusing the same key for different elements or omitting the key will lead to incorrect ref mapping.
fix
Ensure that the key passed to `multiRef.ref(key)` is unique for each element you want to track, typically derived from an array index or unique item ID.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'value') or TypeError: Cannot read properties of null (reading 'value')
Attempting to access properties (like `.value`) on a ref that has not yet been assigned by React, or refers to an unmounted component, or the `key` used in `multiRef.ref(key)` does not correspond to an actual mounted element.
fix
Always check if the ref element exists before accessing its properties: `if (inputElement) { /* access inputElement.value */ }`. Ensure the component is mounted when accessing refs, e.g., in an `useEffect` or event handler, not during render.
React Hook 'useState' cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.
Misuse of `useState` by calling it inside a non-component function or an event handler, instead of at the top level of a functional component.
fix
Ensure `useState(() => new MultiRef())` is called directly within the body of your functional React component, not within any nested functions or event handlers.
Upgrade
Version history
1.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
2 hits · last 30 days
node
2
Resources
react-multi-ref — npm install react-multi-ref · libregistry