Git Product home page Git Product logo

use-media's Introduction

use-media

useMedia React sensor hook that tracks state of a CSS media query.

Install

You can install use-media with npm

npm install --save use-media

or with yarn

yarn add use-media

Usage

With useEffect

import useMedia from 'use-media';
// Alternatively, you can import as:
// import {useMedia} from 'use-media';

const Demo = () => {
  // Accepts an object of features to test
  const isWide = useMedia({minWidth: '1000px'});
  // Or a regular media query string
  const reduceMotion = useMedia('(prefers-reduced-motion: reduce)');

  return (
    <div>
      Screen is wide: {isWide ? 'πŸ˜ƒ' : '😒'}
    </div>
  );
};

With useLayoutEffect

import {useMediaLayout} from 'use-media';

const Demo = () => {
  // Accepts an object of features to test
  const isWide = useMediaLayout({minWidth: '1000px'});
  // Or a regular media query string
  const reduceMotion = useMediaLayout('(prefers-reduced-motion: reduce)');

  return (
    <div>
      Screen is wide: {isWide ? 'πŸ˜ƒ' : '😒'}
    </div>
  );
};

Testing

Depending on your testing setup, you may need to mock window.matchMedia on components that utilize the useMedia hook. Below is an example of doing this in jest:

/test-utilities/index.ts

import {mockMediaQueryList} from 'use-media/lib/useMedia';
// Types are also exported for convienence:
// import {Effect, MediaQueryObject} from 'use-media/lib/types';

export interface MockMatchMedia {
  media: string;
  matches?: boolean;
}

function getMockImplementation({media, matches = false}: MockMatchMedia) {
  const mql: MediaQueryList = {
    ...mockMediaQueryList,
    media,
    matches,
  };

  return () => mql;
}

export function jestMockMatchMedia({media, matches = false}: MockMatchMedia) {
  const mockedImplementation = getMockImplementation({media, matches});
  window.matchMedia = jest.fn().mockImplementation(mockedImplementation);
}

/components/MyComponent/MyComponent.test.tsx

const mediaQueries = {
  mobile: '(max-width: 767px)',
  prefersReducedMotion: '(prefers-reduced-motion: reduce)',
};

describe('<MyComponent />', () => {
  const defaultProps: Props = {
    duration: 100,
  };

  afterEach(() => {
    jestMockMatchMedia({
      media: mediaQueries.prefersReducedMotion,
      matches: false,
    });
  });

  it('sets `duration` to `0` when user-agent `prefers-reduced-motion`', () => {
    jestMockMatchMedia({
      media: mediaQueries.prefersReducedMotion,
      matches: true,
    });

    const wrapper = mount(<MyComponent {...defaultProps} />);
    const child = wrapper.find(TransitionComponent);

    expect(child.prop('duration')).toBe(0);
  });
});

Storing in Context

Depending on your app, you may be using the useMedia hook to register many matchMedia listeners across multiple components. It may help to elevate these listeners to Context.

/components/MediaQueryProvider/MediaQueryProvider.tsx

import React, {createContext, useContext, useMemo} from 'react';
import useMedia from 'use-media';

interface Props {
  children: React.ReactNode;
}

export const MediaQueryContext = createContext(null);

const mediaQueries = {
  mobile: '(max-width: 767px)',
  prefersReducedMotion: '(prefers-reduced-motion: reduce)',
};

export default function MediaQueryProvider({children}: Props) {
  const mobileView = useMedia(mediaQueries.mobile);
  const prefersReducedMotion = useMedia(mediaQueries.prefersReducedMotion);
  const value = useMemo(() => ({mobileView, prefersReducedMotion}), [
    mobileView,
    prefersReducedMotion,
  ]);

  return (
    <MediaQueryContext.Provider value={value}>
      {children}
    </MediaQueryContext.Provider>
  );
}

export function useMediaQueryContext() {
  return useContext(MediaQueryContext);
}

/components/App/App.tsx

import React from 'react';
import MediaQueryProvider from '../MediaQueryProvider';
import MyComponent from '../MyComponent';

export default function App() {
  return (
    <MediaQueryProvider>
      <div id="MyApp">
        <MyComponent />
      </div>
    </MediaQueryProvider>
  );
}

/components/MyComponent/MyComponent.tsx

import React from 'react';
import {useMediaQueryContext} from '../MediaQueryProvider';

export default function MyComponent() {
  const {mobileView, prefersReducedMotion} = useMediaQueryContext();

  return (
    <div>
      <p>mobileView: {Boolean(mobileView).toString()}</p>
      <p>prefersReducedMotion: {Boolean(prefersReducedMotion).toString()}</p>
    </div>
  );
}

use-media's People

Contributors

ahmad-reza619 avatar beefchimi avatar bradwestfall avatar brianmitchl avatar dependabot[bot] avatar jacobrask avatar renovate-bot avatar renovate[bot] avatar ruipserra avatar semantic-release-bot avatar streamich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

use-media's Issues

Support passing null/false or a function to do nothing

Since React has a requirement that hooks be called unconditionally, I find that it sometimes causes hooks to need to support somewhat less elegant APIs than what would be ideal. This is one of those cases:

Since you can't call hooks conditionally, it's helpful to add support for passing a special value to the hook like false, or possibly via a function like () => someCondition ? breakpoint : false to make it do nothing until our condition is met. So in use-media's case it would not set up a matchMedia observer.

AFAIK this is the only way to work around the no-conditional requirement besides moving the hook usage into its own component and conditionally rendering that (not always possible depending on what you're doing).

Any thoughts about supporting that?

Add proper licence

Please consider adding a licence to your project:

...without a license, the default copyright laws apply, meaning that you retain all rights to your source code and no one may reproduce, distribute, or create derivative works from your work.
β€” Licensing a repository - GitHub Docs

(emphasis is mine)

Other than that, it's a common requirement when including it as a dependency for a commercial product.

https://choosealicense.com/

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Support for React 17

It would be very nice to have support for react 17. Anyone who can merge and release a new version?

#156

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/checks.yml
  • actions/checkout v4
  • actions/setup-node v4
.github/workflows/release.yml
  • actions/checkout v4
  • actions/setup-node v4
  • cycjimmy/semantic-release-action v4
npm
package.json
  • @semantic-release/changelog 6.0.3
  • @semantic-release/git 10.0.1
  • @semantic-release/npm 11.0.3
  • @types/react 18.2.64
  • semantic-release 23.0.2
  • typescript 5.4.2
  • react *
travis
.travis.yml
  • node 10

  • Check this box to trigger a request for Renovate to run again on this repository

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npm token.

The npm token configured in the NPM_TOKEN environment variable must be a valid token allowing to publish to the registry https://registry.npmjs.org/.

If you are using Two-Factor Authentication, make configure the auth-only level is supported. semantic-release cannot publish with the default auth-and-writes level.

Please make sure to set the NPM_TOKEN environment variable in your CI with the exact value of the npm token.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

useLayoutEffect

I am using this hook for determining if a user is on a mobile or desktop device, and to conditionally expand or collapse a menu. I am using a useLayoutEffect hook for setting state based on the useMedia hook, but this hook uses useEffect, which causes another render and for the UI to flash into place on the second render, immediately after. I've tried switching the defaultState, but that just moves the problem to the other match case.

How do you feel about a second export that uses useLayoutEffect so consumers can choose which type of effect they would like to use?

Not working. React 18.2.0

npm i --save use-media
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving:
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"18.2.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.1" from [email protected]
npm ERR! node_modules/use-media
npm ERR!   use-media@"*" from the root project

Default should be from matchMedia?

I'm wrestling with getting my media query usage polished. I noticed that on desktop browsers my simple useIsMobile() useMedia call was returning true at first (incorrectly), then false a moment later. This caused a flash of resizing as my components reacted to the change. Here's my hook:

import { useMedia } from 'use-media';

const query = {minWidth: '768px'};

export function useIsMobile(): boolean {
  return !useMedia(query);
}

Looking at the useMedia code I see what I think at least half the problem is. The default state is hardcoded / manually passed, when instead I think it should be something like:

const [state, setState] = useState(() => {
  return !!window.matchMedia(query).matches;
});

The reason I'm not sending you a PR with that change is because when I made it, and added a .log statement inside the closure, I saw the default initializer was being called every single time. It's not clear to me know why that's happening. It should only be called once. Other than being called too often, it worked correctly. I never received the wrong match answer, and it reacted properly to viewport changes.

I'm going to keep digging until I understand this. I wanted to kick this issue out in case you can see the problem more readily.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.