react-use-shared-ref

1.0.7 • Public • Published

useSharedRef

Scrutinizer build (GitHub/Bitbucket) Scrutinizer coverage (GitHub/BitBucket) Scrutinizer code quality (GitHub/Bitbucket)

Introduction

With this hook you can use refs across components without prop drilling. They're stored in a React context instance.

Installation

npm install --save react-use-shared-ref or yarn add react-use-shared-ref.

Usage

First wrap your <App /> inside the RefContextProvider:

import { RefContextProvider } from 'react-use-shared-ref';
 
ReactDOM.render(
  <RefContextProvider>
    <App />
  </RefContextProvider>,
  document.getElementById('root')
);
 

To create a (named) ref, you can use the createRef function that is exposed from the hook. You can then pass this function as a ref to any component.

import useSharedRef from 'react-use-shared-ref';
 
const Component = () => {
  const { createRef } = useSharedRef();
  const ref = createRef('myRef');
 
  return <ChildComponent ref={ref} />;
}

To use the ref in another component, you can use the refs list.

import useSharedRef from 'react-use-shared-ref';
 
const SomeOtherComponent = () => {
  const { refs } = useSharedRef();
  const { myRef } = refs; // Ref to `ChildComponent`
}

The ref does not have a current key as opposed to regular refs, it is either the current value of the ref or it is undefined (not set in the refs object in the context).

Readme

Keywords

none

Package Sidebar

Install

npm i react-use-shared-ref

Weekly Downloads

14

Version

1.0.7

License

MIT

Unpacked Size

321 kB

Total Files

14

Last publish

Collaborators

  • edgarpost