React Multi-Ref Utility

1.0.2 · active · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

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;

view raw JSON →