1.0.2 • Published 11 months ago

react-use-dynamic-refs-hook v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

useDynamicRefs

useDynamicRefs is a custom React hook that allows you to dynamically manage multiple refs in a flexible and efficient manner. This is particularly useful in scenarios where you need to handle multiple refs, such as managing form inputs, DOM elements, or other elements that require useRef.

Installation

You can install useDynamicRefs via npm:

npm install react-use-dynamic-refs-hook

usage

import React, { useEffect } from 'react';
import useDynamicRefs from 'use-dynamic-refs';

function MyForm() {
  const { refs, setRef } = useDynamicRefs({
    username: null,
    email: null,
    password: null,  
    confirmPassword: null,  
  });

  useEffect(() => {
    if (refs.username.current) {
      refs.username.current.focus();
    }
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    const username = refs.username.current?.value;
    const email = refs.email.current?.value;
    const password = refs.password.current?.value; 
    const confirmPassword = refs.confirmPassword.current?.value; 

    console.log('Username:', username);
    console.log('Email:', email);
    console.log('Password:', password); 
    console.log('Confirm Password:', confirmPassword); 
  };

  return (
    <form onSubmit={handleSubmit}>
      <input ref={setRef('username')} type="text" placeholder="Username" />
      <input ref={setRef('email')} type="email" placeholder="Email" />
      <input ref={setRef('password')} type="password" placeholder="Password" /> 
      <input ref={setRef('confirmPassword')} type="password" placeholder="Confirm Password" /> 
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyForm;
1.0.2

11 months ago

1.0.1

11 months ago

1.0.0

11 months ago