use-ref-map

Dynamically generate and reference React ref instances with this handy hook.

Usage no npm install needed!

<script type="module">
  import useRefMap from 'https://cdn.skypack.dev/use-ref-map';
</script>

README

🪝 use-ref-map

npm NPM npm

Dynamically generate and reference React reference instances with this handy hook.

Install

Via npm

npm install use-ref-map

Via Yarn

yarn add use-ref-map

How to use

import useRefMap from 'use-ref-map`

const ExampleComponent = ({ buttonData }) => {
  const { getRef, setRef } = useRefMap()

  const handleSubmit = (evt) => {
    evt.preventDefault()

    const email = getRef('email_input')?.current?.value
    const password = getRef('password_input')?.current?.value
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" ref={setRef('email_input')} />
      <input type="password" ref={setRef('password_input')} />
    </form>
  )
}

This is a silly example, but should give you an idea of how to use this hook. This is most useful when dealing with an array of components that require unique ref instance props passed to each, using an example key of something like, dynamic-ref-${id}.

License

MIT © Ryan Hefner