1.0.6 • Published 3 years ago

@seznam/compose-react-refs v1.0.6

Weekly downloads
63,894
License
ISC
Repository
github
Last release
3 years ago

Compose react refs

Build Status npm License npm type definitions

A simple utility for composing two or more react refs (ref objects and callbacks are both supported and can be mixed) into a single callback ref. This enables you to effectively set multiple refs on the same component/element.

This utility does not use react hooks, therefore it can be used in class components (and even outside of react world) safely.

Installation

compose-react-refs is available as npm package, you can use npm to install it:

npm install --save @seznam/compose-react-refs

Usage

The following example shows usage in a functional component that composes an external ref with its own ref it uses to focus the renderer <input> element:

import * as React from 'react'
import composeRefs from '@seznam/compose-react-refs'

export default React.forwardRef((props, externalRef) => {
  const myRef = React.useRef(null)
  
  React.useEffect(() => {
    myRef.current.focus()
  })

  // No need to worry about nulls and undefined refs here, they will be
  // filtered out automatically.
  return <input {...props} ref={composeRefs(myRef, externalRef)}/>
})

The composeRefs function allows combining any number of refs:

import * as React from 'react'
import composeRefs from '@seznam/compose-react-refs'

export default React.forwardRef((props, externalRef) => {
  const myRef = React.useRef(null)
  const otherRef = React.useRef(null)
  return <input {...props} ref={composeRefs(myRef, null, undefined, otherRef, props.extraRef, externalRef)}/>
})

The refs will be updated in the order in which they were provided to the composeRefs function. The composed ref passed to react is cached (no need to use useMemo in your code), improving performance and preventing unexpected ref updates.

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago

0.0.0

5 years ago