https://github.com/palmerhq/react-register-nodes
Register DOM Nodes in React
https://github.com/palmerhq/react-register-nodes
hooks react react-dom react-hooks
Last synced: about 1 year ago
JSON representation
Register DOM Nodes in React
- Host: GitHub
- URL: https://github.com/palmerhq/react-register-nodes
- Owner: palmerhq
- License: mit
- Created: 2018-08-06T14:16:18.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2021-09-14T10:07:13.000Z (over 4 years ago)
- Last Synced: 2025-05-07T00:07:16.259Z (about 1 year ago)
- Topics: hooks, react, react-dom, react-hooks
- Language: TypeScript
- Homepage:
- Size: 190 KB
- Stars: 32
- Watchers: 2
- Forks: 3
- Open Issues: 3
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-register-nodes
Register DOM nodes within a context. Helpful for UI where many siblings need to know about each other. A common example is scrolling to the first error after a form submission.
## Installation
```
yarn add react-register-nodes
```
## Examples
* Scroll to first error - https://codesandbox.io/s/10363x25oq
* Deep nested node registration - https://codesandbox.io/s/lxrno4nk9
## Usage
```js
import * as React from "react";
import { render } from "react-dom";
import {
NodeManager,
useNodes,
useRegisteredRef
} from "react-register-nodes";
const Example = () => {
// useRegisteredRef will return a ref to be used on the DOM node you'd like
// to register. It accepts a string key to register the node under.
const ref = useRegisteredRef("shallow");
// useNodes will return an object containing any DOM nodes we have assigned our refs to
// in this case, our div will be mapped to the key 'shallow'
const nodes = useNodes();
return (
Register Me!
Registered Nodes:
{JSON.stringify(Object.keys(nodes), null, 2)}
);
};
const rootElement = document.getElementById("root");
render(
,
rootElement
);
```
## API Reference
### ``
This is the Context Provider. Must be above any components that call the `use*` hooks.
### `useRegisteredRef(key: string): HTMLElement | undefined`
Returns a `ref` to be passed to your DOM node. The node assigned to `ref.current` will be registered with the nearest NodeManager. Accepts an id to serve as the key to register the node under.
### `useNodes(): { [key: string]: HTMLElement }`
Returns an object of all registered nodes. Nodes are keyed by the key you passed to `useRegisteredRef`.
### `useOrderedNodes(sorter: (nodes: HTMLElement[]) => HTMLElement[]): HTMLElement[]`
Returns all registered nodes in the order specified by `sorter`. Uses [DOM order](https://gist.github.com/Justineo/ec7275cda82e986fc47b) by default.
## Author
- Nathan Force [@forcetheissue](https://twitter.com/forcetheissue)