Coder Social home page Coder Social logo

gatsby-plugin-breakpoints's Introduction

gatsby-plugin-breakpoints

Gatsby plugin providing breakpoints using React Hooks

travis build travis build npm version NPM downloads dependencies status dev dependencies status

commitizen semantic-release prettier license

Install

npm i gatsby-plugin-breakpoints

or

yarn add gatsby-plugin-breakpoints

Include the plugin in your gatsby-config.js file :

/* gatsby-config.js */

module.exports = {
    plugins: ['gatsby-plugin-breakpoints'],
};

Usage

Functional Components

Import the useBreakpoint hook anywhere in your app.

This hook provides four default breakpoints as boolean :

name breakpoints
xs max-width: 320px
sm max-width: 720px
md max-width: 1024px
l max-width: 1536px
/* yourFunctionalComponentOrPage.js */

import { useBreakpoint } from 'gatsby-plugin-breakpoints';

import MobileOnlyComponent from './your/component/path';
// ...

const MyComponent = () => {
    const breakpoints = useBreakpoint();

    return (
        <AnyComponent>
            {/* Anything */}

            {/* <MobileOnlyComponent /> will only be displayed if max-width <= 320px  */}
            {breakpoints.xs ? <MobileOnlyComponent /> : null}
        </AnyComponent>
    );
};

export default MyComponent;

Class Components

Import the withBreakpoints Higher Order Component anywhere in your app.

This HOC adds a breakpoints props to your component, providing four default breakpoints as boolean :

name breakpoints
xs max-width: 320px
sm max-width: 720px
md max-width: 1024px
l max-width: 1536px
/* yourClassComponent.js */

import { withBreakpoints } from 'gatsby-plugin-breakpoints';

import MobileOnlyComponent from './your/component/path';
// ...

class Test extends React.Component {
    render() {
        const { breakpoints } = this.props;
        {
            /* <MobileOnlyComponent /> will only be displayed if max-width <= 320px  */
        }
        return breakpoints.xs ? (
            <MobileOnlyComponent />
        ) : (
            <div>Content hidden only on mobile</div>
        );
    }
}

export default withBreakpoints(Test);

Options

You can set your own queries like this :

// in gatsby-config.js

const myCustomQueries = {
    xs: '(max-width: 320px)',
    sm: '(max-width: 720px)',
    md: '(max-width: 1024px)',
    l: '(max-width: 1536px)',
    xl: ...,
    portrait: '(orientation: portrait)',
};

module.exports = {
    plugins: [
        {
            resolve: "gatsby-plugin-breakpoints",
            options: {
                queries: myCustomQueries,
            },
        },
    ],
}

Default values

const defaultQueries = {
    xs: '(max-width: 320px)',
    sm: '(max-width: 720px)',
    md: '(max-width: 1024px)',
    l: '(max-width: 1536px)',
};

Note (only for test)

If you need to import <BreakpointProvider /> for testing you can do it like so :

import { BreakpointProvider } from 'gatsby-plugin-breakpoints';

In case you need full context, you can import it too :

import { BreakpointContext } from 'gatsby-plugin-breakpoints';

Contributing

Contributions are welcome ! See contributing guidelines

License

MIT

Copyright (c) 2019 Jimmy Beldone

gatsby-plugin-breakpoints's People

Contributors

dependabot[bot] avatar jimmybeldone avatar renovate-bot avatar renovate[bot] avatar semantic-release-bot 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

Watchers

 avatar  avatar

gatsby-plugin-breakpoints's Issues

useBreakpoint returns empty object

Hello!

I'm brand new to gatsby (v3) and am trying to leverage this plugin. I've installed it with defaults. No matter what I do useBreakpoint() returns an empty object.

I've tried manually wrapping my Layout with a BreakpointProvider and providing my own queries, but still nothing.

Is there something missing from the README?

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.

feat: export BreakpointContext

Hey Jimmy thanks for the plugin. I have a tiny request.

I wonder if you could expose BreakpointContext in a next release.

I ran into a scenario (niche) while trying to put together a Gatsby starter theme for pure canvas-driven ThreeJS projects. i.e no DOM elements just Canvas as the layout root.

The main cocktail is gatsby, react-three-fiber and @react-three/drei.

The issue is that react-three-fiber's Canvas (which will be the root element) doesn't allow ContextAPI consumption by react-three-fiber children unless its proxied via a "context bridge". @react-three/drei offers a solution via useContextBridge().

As you can see this hook proxies your contexts, so that they can be consumed by any child (.Shapes, Geometries etc..
) within the Canvas tree by the usual React.useContext API.

I'd love to test your plugin for dealing with breakpoints within this Canvas ecosystem.

P.S - I've successfully proxied some local contexts I created but hit this roadblock with your plugin.

Dependency Dashboard

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

Warning

These dependencies are deprecated:

Datasource Name Replacement PR?
npm babel-eslint Available

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency rimraf to v5.0.10
  • chore(deps): update dependency eslint to v8.57.1
  • chore(deps): update dependency eslint-plugin-jest to v27.9.0
  • chore(deps): update dependency eslint-plugin-jsx-a11y to v6.10.0
  • chore(deps): update dependency eslint-plugin-prettier to v5.2.1
  • chore(deps): update dependency eslint-plugin-react to v7.36.1
  • chore(deps): update dependency react to v18.3.1
  • chore(deps): update actions/cache action to v4
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-plugin-jest to v28
  • chore(deps): update dependency husky to v9
  • chore(deps): update dependency rimraf to v6
  • chore(deps): update dependency semantic-release to v24
  • ๐Ÿ” Create all rate-limited PRs at once ๐Ÿ”

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/publish.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/cache v3
.github/workflows/test.yml
  • actions/checkout v3
  • actions/setup-node v3
  • actions/cache v3
npm
package.json
  • @babel/runtime ^7.23.2
  • @babel/cli 7.23.0
  • @babel/core 7.23.3
  • @babel/eslint-parser 7.23.3
  • @babel/preset-env 7.23.3
  • @babel/preset-react 7.23.3
  • @semantic-release/changelog 6.0.3
  • @semantic-release/git 10.0.1
  • babel-eslint 10.1.0
  • babel-preset-gatsby-package 3.12.0
  • commitizen 4.3.0
  • cross-env 7.0.3
  • cz-conventional-changelog 3.3.0
  • devmoji 2.3.0
  • eslint 8.53.0
  • eslint-config-airbnb-base 15.0.0
  • eslint-config-prettier 9.0.0
  • eslint-plugin-import 2.29.0
  • eslint-plugin-jest 27.6.0
  • eslint-plugin-jsx-a11y 6.8.0
  • eslint-plugin-prettier 5.0.1
  • eslint-plugin-react 7.33.2
  • husky 8.0.3
  • lint-staged 15.1.0
  • prettier 3.1.0
  • prop-types 15.8.1
  • react 18.2.0
  • rimraf 5.0.5
  • semantic-release 22.0.7
  • gatsby ^4.0.0 || ^5.0.0
  • prop-types ^15.7.2
  • react ^16.13.1 || ^17.0.0 || ^18.0.0

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

Package installed via npm has old peerDependencies

Even though, I have "gatsby-plugin-breakpoints": "^1.3.9", in my package.json file, after npm install, the package.json from gatsby-plugin-breakpoints looks like below.

You can see that it still says "gatsby": "^2.0.0 || ^3.0.0 || ^4.0.0" instead of "gatsby": "^2.0.0 || ^3.0.0 || ^4.0.0 || ^5.0.0".

This is preventing me from upgrading to Gatsby5.

{
  "name": "gatsby-plugin-breakpoints",
  "version": "1.3.9",
  "description": "Gatsby plugin providing breakpoints using React Hooks",
  "keywords": [
    "gatsby",
    "gatsby-plugin",
    "gatsby-plugin-breakpoints",
    "breakpoints",
    "media query",
    "media queries",
    "hooks",
    "responsive"
  ],
  "main": "index.js",
  "author": "Jimmy Beldone <[email protected]>",
  "homepage": "https://github.com/JimmyBeldone/gatsby-plugin-breakpoints",
  "repository": {
    "type": "git",
    "url": "https://github.com/JimmyBeldone/gatsby-plugin-breakpoints.git"
  },
  "bugs": {
    "email": "[email protected]",
    "url": "https://github.com/JimmyBeldone/gatsby-plugin-breakpoints/issues"
  },
  "scripts": {
    "commit": "git-cz",
    "lint": "eslint src --fix",
    "pretty": "prettier --write 'src/**/*.js'",
    "test": "echo 'No test specified'",
    "prepare": "cross-env NODE_ENV=production yarn build && husky install",
    "build": "babel src --out-dir .",
    "semantic-release": "semantic-release"
  },
  "license": "MIT",
  "private": false,
  "devDependencies": {
    "@babel/cli": "7.19.3",
    "@babel/core": "7.19.3",
    "@babel/eslint-parser": "7.19.1",
    "@babel/preset-env": "7.19.4",
    "@babel/preset-react": "7.18.6",
    "@semantic-release/changelog": "6.0.1",
    "@semantic-release/git": "10.0.1",
    "babel-eslint": "10.1.0",
    "babel-preset-gatsby-package": "2.24.0",
    "commitizen": "4.2.5",
    "cross-env": "7.0.3",
    "cz-conventional-changelog": "3.3.0",
    "devmoji": "2.3.0",
    "eslint": "8.25.0",
    "eslint-config-airbnb-base": "15.0.0",
    "eslint-config-prettier": "8.5.0",
    "eslint-plugin-import": "2.26.0",
    "eslint-plugin-jest": "27.1.2",
    "eslint-plugin-jsx-a11y": "6.6.1",
    "eslint-plugin-prettier": "4.2.1",
    "eslint-plugin-react": "7.31.10",
    "husky": "8.0.1",
    "lint-staged": "13.0.3",
    "prettier": "2.7.1",
    "prop-types": "15.8.1",
    "react": "18.2.0",
    "rimraf": "3.0.2",
    "semantic-release": "19.0.5"
  },
  "lint-staged": {
    "{src}/**/*.js": [
      "eslint --fix",
      "prettier --write"
    ]
  },
  "config": {
    "commitizen": {
      "path": "./node_modules/cz-conventional-changelog"
    }
  },
  "dependencies": {
    "@babel/runtime": "^7.19.4"
  },
  "peerDependencies": {
    "gatsby": "^2.0.0 || ^3.0.0 || ^4.0.0",
    "prop-types": "^15.7.2",
    "react": "^16.13.1 || ^17.0.0 || ^18.0.0"
  }
}

Using the BreakpointContext Provider outside of pages in a component of wrapRootElement

Not too familiar with the whole context stuff so I'm probably just overlooking something, just can't figure it out.

Basically, I am trying to use your breakpoints in a component of my header. That header is in a layout component which is wrapped around the page using wrapRootElement (needs to be for some other stuff to work).

Now when I use the breakpoint hook in the header, I get the error that it needs to be in the BreakpointContext Provider. I imported the provider and added it to my component that wraps everything. The error is gone which makes me think it now has access to it. However, it is always empty so I can't target breakpoints.xs etc.

I was thinking I have to provide the correct value to the provider and tried poking around your code to find out which value to set. I tried the queryMatch and setQueryMatch but that's probably wrong.

Which would be the correct value? Or am I tackling this completely wrong?

Here is the element that wraps my pages:

import React, { useState } from "react"
import Layout from "../layout"
import { BreakpointContext } from "gatsby-plugin-breakpoints"

export const myContext = React.createContext()

const Provider = props => {
  const [logoPlayed, setLogoPlay] = useState(false)
  const [trans, setTrans] = useState()
  const [locale, setLocale] = useState()
  const [queryMatch, setQueryMatch] = useState({})

  return (
    <myContext.Provider
      value={{
        logoPlayed,
        changeTheme: () => setLogoPlay(true),
        trans,
        setTrans,
        locale,
        setLocale,
      }}
    >
      <BreakpointContext.Provider value={{ queryMatch, setQueryMatch }}>
        <Layout
          trans={trans ? trans : null}
          locale={locale ? locale.slice(0, 2).toLowerCase() : null}
        >
          {props.children}
        </Layout>
      </BreakpointContext.Provider>
    </myContext.Provider>
  )
}

export default ({ element }) => <Provider>{element}</Provider>

Any pointers would be much appreciated :)

useBreakPoint returning an empty object

I'm using Gatsby v4.24.5 and gatsby-plugin-breakpoints v1.3.9, but I can't seem to be able to fetch the breakpoints I need.

import { useBreakpoint } from 'gatsby-plugin-breakpoints';
const breakpoints = useBreakpoint();
console.log({ breakpoints });

Result:
image

Here's my gatsby-config.js
image

I tried changing my gatsby-config.js to the default configs for the plugin as well, but it didn't work either

Extra render happens because breakpoints are set from a useEffect.

Hi! I am running into a CLS issue as one of the child components I have that uses the useBreakpoints() hook, gets the default empty object {} from useBreakpoints() on the first render. This causes the child component that relies on the breakpoints to not render properly for the right window size.

After the child has rendered, the useEffect that calculates the breakpoints in the provider is triggered, and a second render is started with the correct value of breakpoints. This causes the page to have a huge CLS hit as the child object is quite large, pushing other components down the screen.

Has anyone else run into this issue?

Gatsby build crash

I test the plugin in a fresh Gatsby install.
It works fine in dev mode, but crash un build.

I try to add the Provider with no luck :(

Thanks so much!!

  78 |
  79 |   if (context === defaultValue) {
> 80 |     throw new Error('useBreakpoint must be used within BreakpointProvider');
     |           ^
  81 |   }
  82 |
  83 |   return context;


  WebpackError: useBreakpoint must be used within BreakpointProvider

  - BreakpointProvider.js:80 useBreakpoint
    node_modules/gatsby-plugin-breakpoints/BreakpointProvider.js:80:11

Better documentation and solution for testing Functional Components using useBreakpoint

I am following the README in using the useBreakpoint() function to retrieve breakpoints like so in my functional component

const Layout = ({ ... }: Props) => {
    const breakpoints = useBreakpoint()

    return (
        ....
        breakpoints.md ? <Header /> : <MobileHeader />
    )
}

This works perfectly fine to build and run, but when I run a Jest unit test, I get an error saying to use BreakpointProvider. The only documentation on this in your README is "import it this way" with no details on how to use it. I was finally able to get it to work if I change my code to:

const Layout = ({ ... }: Props) => (
    ....
    <BreakpointProvider>useBreakpoint().md</BreakpointProvider> ? <Header /> : <MobileHeader />
)

This is extremely weird syntax in order to use that useBreakpoint function... Is there a different solution to this?

Storybook integration error

Hi, first of all, thanks a lot for this plugin.
I am using storybook, and I got this error on storybook after setting up this plugin on a component :
useBreakpoint must be used within BreakpointProvider

I tried using the <BreakpointProvider /> tag with no success.

it's not blocking me because it's working perfectly on my gatsby project, but it's a little annoying :D

thanks

Does this work for latest Gatsby/React version?

Got this error when trying to install to a new project:

`# npm resolution error report

2022-07-06T17:03:32.620Z

While resolving: [email protected]
Found: [email protected]
node_modules/react
react@"^18.1.0" from the root project
peer react@"^16.9.0 || ^17.0.0 || ^18.0.0" from [email protected]
node_modules/gatsby
gatsby@"^4.18.0" from the root project
peer gatsby@"^2.0.0 || ^3.0.0 || ^4.0.0" from [email protected]
node_modules/gatsby-plugin-breakpoints
gatsby-plugin-breakpoints@"" from the root project
peer react@"^18.2.0" from [email protected]
node_modules/react-dom
react-dom@"^18.1.0" from the root project
peer react-dom@"^16.9.0 || ^17.0.0 || ^18.0.0" from [email protected]
node_modules/gatsby
gatsby@"^4.18.0" from the root project
peer gatsby@"^2.0.0 || ^3.0.0 || ^4.0.0" from [email protected]
node_modules/gatsby-plugin-breakpoints
gatsby-plugin-breakpoints@"
" from the root project

Could not resolve dependency:
peer react@"^16.13.1 || ^17.0.0" from [email protected]
node_modules/gatsby-plugin-breakpoints
gatsby-plugin-breakpoints@"*" from the root project

Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.`

BreakpointProvider is not exported.

Hello, I am using this library to render some responsive components in a gatsby project. It works fine in runtime.
On the other hand, I cannot test the components that are using the useBreakpoint.

To test them, I need to wrap my testing component with the Breakpoint provider. The Breakpoint provider is not exported at the current release version.

for example in a test.js file:

import { BreakpointProvider } from ('gatsby-plugin-breakpoints');

it('should render with breakpoints', () => {
      const wrapper = render(<BreakpointProvider><NavBar isFixed menuData={defaultMenuData} /></BreakpointProvider> );
})

Proposed solution

To export the Breakpoint provider from the src/index.js file:

import { useBreakpoint, BreakpointProvider } from './BreakpointProvider';
...
export { useBreakpoint, withBreakpoints, BreakpointProvider };

Could not find a declaration file for module 'gatsby-plugin-breakpoints'. '/node_modules/gatsby-plugin-breakpoints/index.js' implicitly has an 'any' type.

Having problems with getting the breakpoint working. I went along with the example but breakpoint.md seems to always be false. VS Code is showing this "Could not find a declaration file for module 'gatsby-plugin-breakpoints'. '/node_modules/gatsby-plugin-breakpoints/index.js' implicitly has an 'any' type.".

Tried npm install @types/gatsby-plugin-breakpoints but it didn't exist.

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.