npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-context-refs

v0.2.1

Published

Library to manipulate react refs via context.

Downloads

1,158

Readme

react-context-refs

npm version

Library to get react refs via context. For example it can be useful when you need to scroll or set focus to some field after form validation and you have a deep nested components hierarchy.

Fields focus example

First, you should add RefProvider.

main.js

import * as React from "react";
import { render } from "ract-dom";
import { RefProvider } from "react-context-refs";
import Page from "./form";

// ...

render(
  <RefProvider>
    <Page />
  </RefProvider>,
  element
);

Then you need to add each field to context refs storage. You can add some metadata to your refs. In this example we add hasError property to refs.

someField.js

import * as React from "react";
import { useContextRef } from "react-context-refs";

export default ({ value, onChange, hasError }) => {
  const setRef = useContextRef({ hasError });

  return (
    <input
      style={hasError ? { backgroundColor: "#FFCABF" } : {}}
      ref={setRef}
      value={value}
      onChange={onChange}
    />
  );
};

And then in some root component you can get all refs and set focus to any of them.

import * as React from "react";
import { useRefs } from "react-context-refs";
import { compareOrder } from "sort-nodes";

// ...

export default props => {
  // ...

  const refs = useRefs();
  const onSubmit = () => {
    if (!isFormValid()) {
      const firstFieldWithError = refs
        // remove fields without errors
        .filter(ref => ref.meta.hasError)
        // get current value of refs
        .map(ref => ref.current)
        // sort by order in dom tree
        .sort(compareOrder)[0];

      firstFieldWithError.focus();
      return;
    }
    // ...
  };

  return <Form {...formProps} onSubmit={onSubmit} />;
};

API

RefProvider

This provider creates a storage of refs and let you use other methods of react-context-refs.

A storage contains an array of refs and two additional fields for each ref: type and meta.

useRefs

useRefs returns an array of refs from the storage. Each ref has the following fields:

  • current - value of ref
  • type - string to determine type of ref if there are several types of ref in the storage
  • meta - any additional data

You can use useRefs without parameters or you can pass a string to useRefs and it will return only refs of the corresponding type.

import { useRefs } from "react-context-refs";

// ...
const myInputs = useRefs("my-input");

useContextRef

This hook returns a method to set ref.

You add pass a metadata to ref or a metadata and type.

The first form of useContextRef has the only parameter - meta.

The second has two parameters:

  • type string
  • meta any
import { useContextRef } from "react-context-refs";

// ...
const setRef = useContextRef("my-ref-type", { additionalValue: true });

Typings (typescript)

If you want to add strong types to your refs you can set type of current and meta for each type.

You can do it with this code:

declare module ReactContextRefs {
  export interface Refs {
    myInput: { current: HTMLInputElement; meta: { hasError: boolean } };
  }
}

Here we has set types of current and meta for each ref which has type myInput.

import { useRefs } from "react-context-refs";

// now myInputs has type an array of
// {
// 	type: "myInput",
// 	current: HTMLInputElement,
// 	meta: {hasError: boolean},
// }
const myInputs = useRefs("myInput");