https://github.com/seznam/compose-react-refs
A small utility that composes two or more react refs into a ref callback.
https://github.com/seznam/compose-react-refs
Last synced: 9 days ago
JSON representation
A small utility that composes two or more react refs into a ref callback.
- Host: GitHub
- URL: https://github.com/seznam/compose-react-refs
- Owner: seznam
- License: isc
- Created: 2019-06-11T10:38:54.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2021-03-19T12:09:59.000Z (about 4 years ago)
- Last Synced: 2024-04-26T11:01:02.174Z (12 months ago)
- Language: TypeScript
- Size: 134 KB
- Stars: 113
- Watchers: 3
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- jimsghstars - seznam/compose-react-refs - A small utility that composes two or more react refs into a ref callback. (TypeScript)
README
# Compose react refs
[](https://travis-ci.org/seznam/compose-react-refs)
[](https://www.npmjs.com/package/@seznam/compose-react-refs)
[](LICENSE)
A simple utility for composing two or more
[react refs](https://reactjs.org/docs/refs-and-the-dom.html) (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](https://github.com/facebook/react/issues/13029).This utility does not use
[react hooks](https://reactjs.org/docs/hooks-intro.html), 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 `` element:```typescript jsx
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
})
```The `composeRefs` function allows combining any number of refs:
```typescript jsx
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
})
```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`](https://reactjs.org/docs/hooks-reference.html#usememo) in your
code), improving performance and preventing
[unexpected ref updates](https://reactjs.org/docs/refs-and-the-dom.html#caveats-with-callback-refs).