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-hook-media

v1.1.1

Published

A lightweight and tree-shakable library for working with media queries in React applications, providing responsive behavior and conditional rendering based on media query conditions.

Downloads

129

Readme

react-hook-media

React Hook Media is a lightweight and tree-shakable library that provides tools for working with media queries in React applications. It allows you to easily incorporate responsive behavior and conditional rendering based on media query conditions.

The library also provides a server-side rendering (SSR) feature through the configureNodeEnv method. It allows you to configure the Node environment to simulate different media query results during server-side rendering.

React Hook Media is simple to use and integrates seamlessly with React applications, providing a convenient way to handle media queries and create responsive UI components.

Installation

using npm:

npm install --save react-hook-media

or yarn:

yarn add react-hook-media

or pnpm:

pnpm add react-hook-media

Example

import {
  useMatchMedia,
  configureNodeEnv,
  MatchMedia,
  MatchMediaHydrationProvider,
} from "react-hook-media";

const MyComponent = () => {
  const isDesktop = useMatchMedia("(min-width: 900px)");

  return (
    <div>
      {isDesktop ? "desktop" : "mobile"}
      <MatchMedia query="(width < 900px)" otherwise={"desktop"}>
        mobile
      </MatchMedia>
      <MatchMedia
        query={["(width < 576px)", "(width > 1024px)"]}
        render={(isMobile, isDesktop) =>
          isMobile ? "mobile" : isDesktop ? "desktop" : "tablet"
        }
      />
    </div>
  );
};

// code bellow is for server-side rendering, ignore it if you don't use it
const Page = ({ mediaHydrationCtx }) => (
  <MatchMediaHydrationProvider value={mediaHydrationCtx}>
    <MyComponent />
  </MatchMediaHydrationProvider>
);

export const getServerSideProps = async () => {
  return {
    props: {
      mediaHydrationCtx: configureNodeEnv({ width: 1000 }),
    },
  };
};

API

useMatchMedia

const useMatchMedia: (mediaQuery: string) => boolean;

Custom hook that provides the functionality of the matchMedia method as a React hook.

In a Node environment, where media queries are not supported, you must use the configureNodeEnv method to simulate different device conditions, like in example.

Returns true if the media query matches, false otherwise.


MatchMedia

type MatchMediaProps<T extends string | string[] = string> = {
  /**
   * The media query to evaluate.
   */
  query: T;
} & (
  | (T extends string
      ? PropsWithChildren<{
          /**
           * The content to render if the media query does not match (optional).
           */
          otherwise?: ReactNode;
        }>
      : never)
  | {
      render(
        ...isMatched: T extends string | [string]
          ? [boolean]
          : {
              [key in keyof T]: boolean;
            }
      ): ReactNode;
    }
);

const MatchMedia: <const T extends string | string[]>(
  props: MatchMediaProps<T>
) => ReactNode;

Evaluates the provided media query and renders its children if the media query matches. Optionally, you can also provide an otherwise prop to specify the content to render if the media query does not match. Alternatively, you can provide a render prop to conditionally render content based on the media query evaluation.

It uses the useMatchMedia hook under the hood


configureNodeEnv

const configureNodeEnv: (
  config: MediaQueryEnvironmentConfig
) => MatchMediaHydrationContext;

Configures the Node environment for server-side rendering (SSR).

This function is used to set up the environment for the useMatchMedia hook when running React components on the server. It allows you to provide a custom configuration object to simulate different media query results.

The configuration object should contain properties that match the media query conditions you want to simulate. For example, if you configure it with { width: 768 }, it will simulate the viewport width as if it were 768 pixels wide, affecting the results returned by useMatchMedia when evaluating media queries related to width.

Returns a MatchMediaHydrationContext object that should be passed to the MatchMediaHydrationProvider.


MatchMediaHydrationProvider

type MatchMediaHydrationContext = Record<string, boolean>;

const MatchMediaHydrationProvider: Provider<MatchMediaHydrationContext>;

A React context provider component for hydrating match media values.


License

MIT © Krombik