1.0.7 • Published 5 years ago

react-use-shared-ref v1.0.7

Weekly downloads
17
License
MIT
Repository
github
Last release
5 years ago

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).

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.0

5 years ago