{"library":"react-multi-ref","title":"React Multi-Ref Utility","description":"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.","language":"javascript","status":"active","last_verified":"Sun Apr 19","install":{"commands":["npm install react-multi-ref"],"cli":null},"imports":["import MultiRef from 'react-multi-ref';","const [itemRefs] = useState(() => new MultiRef());","<input ref={itemRefs.ref(i)} />"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { useState } from 'react';\nimport MultiRef from 'react-multi-ref';\n\nfunction MyDynamicForm() {\n  // Initialize MultiRef using useState to persist the instance across renders\n  const [inputRefs] = useState(() => new MultiRef());\n\n  // Generate 5 input fields, assigning a ref to each using its index as a key\n  const inputElements = new Array(5).fill(null).map((_, i) => (\n    <div key={i} style={{ marginBottom: '10px' }}>\n      <label>\n        Input {i + 1}: \n        <input type=\"text\" ref={inputRefs.ref(i)} placeholder={`Value for item ${i + 1}`} />\n      </label>\n    </div>\n  ));\n\n  // Event handler to collect all input values\n  function handleSubmit() {\n    const values = [];\n    inputRefs.map.forEach((inputElement, key) => {\n      if (inputElement) {\n        values.push(`Key ${key}: ${inputElement.value}`);\n      }\n    });\n    alert(\"Current input values:\\n\" + values.join('\\n'));\n  }\n\n  return (\n    <div>\n      <h3>Dynamic Input Form</h3>\n      {inputElements}\n      <button onClick={handleSubmit} style={{ marginTop: '20px', padding: '10px 15px' }}>\n        Get All Input Values\n      </button>\n    </div>\n  );\n}\n\n// To run this example in a React application:\n// export default MyDynamicForm;","lang":"typescript","description":"Demonstrates how to use MultiRef in a functional React component to manage references to multiple dynamically created input elements and retrieve their values.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}