Coder Social home page Coder Social logo

mg901 / styled-breakpoints Goto Github PK

View Code? Open in Web Editor NEW
545.0 8.0 24.0 10.13 MB

Simple and powerful breakpoints for styled components and emotion.

Home Page: https://www.npmjs.com/package/styled-breakpoints

License: MIT License

JavaScript 82.45% Shell 0.37% TypeScript 17.18%
styled-components breakpoints breakpoint media-queries css-in-js css-in-react media react emotion typescript preact media-query styled-media-query responsive-design responsive-layout

styled-breakpoints's Introduction


styled-breakpoints
GitHub Workflow Status coverage status npm bundle size npm downloads npm version

Simple and powerful tool for creating media queries with SSR support.

Styled Components Logo     OR    Emotion logo



🌼 Preview

Inside components.

const Box = styled.div`
  background-color: pink;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    background-color: hotpink;
  }

  ${({ theme }) => theme.breakpoints.up('md')} {
    background-color: red;
  }
`;

Outside components.

import { useTheme } from 'styled-components'; // or '@emotion/react'

const Layout = () => {
  const { breakpoints } = useTheme();
  const isMd = useMediaQuery(breakpoints.up('md'));

  return <>{isMd && <Box />}</>;
};

Examples

👉🏻 Mobile First

From smallest to largest


👉🏻 Desktop First

From largest to smallest


👉🏻 Hooks API



📖 Documentation


🧐 Core concepts

  • Breakpoints act as the fundamental elements of responsive design. They enable you to control when your layout can adapt to a specific viewport or device size.

  • Utilize media queries to structure your CSS based on breakpoints. Media queries are CSS features that allow you to selectively apply styles depending on a defined set of browser and operating system parameters. The most commonly used media query property is min-width.

  • The objective is mobile-first, responsive design. Styled Breakpoints aims to apply the essential styles required for a layout to function at the smallest breakpoint. Additional styles are then added to adjust the design for larger devices. This approach optimizes your CSS, enhances rendering speed, and delivers an excellent user experience.


Getting Started

🚩 Installation

npm install styled-breakpoints@latest

# or

yarn add styled-breakpoints@latest

Configuration

🚩 Available breakpoints

Styled Breakpoints includes six default breakpoints, often referred to as grid tiers, for building responsive designs. These breakpoints can be customized.

const breakpoints = {
  xs: '0px',
  sm: '576px',
  md: '768px',
  lg: '992px',
  xl: '1200px',
  xxl: '1400px',
};

Each breakpoint has been carefully selected to accommodate containers with widths that are multiples of 12. The breakpoints also represent a subset of common device sizes and viewport dimensions, although they do not specifically target every use case or device. Instead, they provide a robust and consistent foundation for building designs that cater to nearly any device.


🚩 Default Configuration

theme/config.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

export const theme = createStyledBreakpointsTheme();


Customization

🚩 Breakpoints

theme/config.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

export const theme = createStyledBreakpointsTheme({
  breakpoints: {
    small: '100px',
    medium: '200px',
    large: '300px',
    xLarge: '400px',
    xxLarge: '500px',
  },
});

🎨 Merge with Another Theme

theme/config.ts

import { createStyledBreakpointsTheme } from 'styled-breakpoints';

export const primaryTheme = {
  fonts: ['sans-serif', 'Roboto'],
  fontSizes: {
    small: '1em',
    medium: '2em',
    large: '3em',
  },
} as const;

export const theme = {
  ...primaryTheme,
  ...createStyledBreakpointsTheme(),
};


💅 Using with Styled Components

🚩 Installation
npm install styled-components

# or

yarn add styled-components

theme/styled.d.ts

import 'styled-components';
import { theme } from './theme/config';

type MyTheme = typeof theme;

declare module 'styled-components' {
  export interface DefaultTheme extends MyTheme {}
}


👩‍🎤 Using with Emotion

🚩 Installation
npm install @emotion/{styled,react}

# or

yarn add @emotion/{styled,react}

theme/emotion.d.ts

import '@emotion/react';
import { theme } from './theme/config';

type MyTheme = typeof theme;

declare module '@emotion/react' {
  export interface Theme extends MyTheme {}
}


🚀 Integration to App


app.tsx

import styled { ThemeProvider } from 'styled-components'; // or '@emotion/react'
import { theme } from './theme/config';

const Box = styled.div`
  display: none;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    display: block;
  }
`;

const App = () => (
  <ThemeProvider theme={theme}>
    <Box>🥳</Box>
  </ThemeProvider>
);

Media queries API

🚀 Caching is implemented in all functions to optimize performance.


Min-width - up


Type declaration
  declare function up(
    min: T,
    orientation?: 'portrait' | 'landscape'
  ) => string
const Box = styled.div`
  display: none;

  ${({ theme }) => theme.breakpoints.up('sm')} {
    display: block;
  }
`;

Will be converted to pure css:
@media (min-width: 768px) {
  display: block;
}


Max-width - down

We occasionally use media queries that go in the other direction (the given screen size or smaller):


Type declaration
  declare function down(
    max: string,
    orientation?: 'portrait' | 'landscape'
  ) => string
const Box = styled.div`
  display: block;

  ${({ theme }) => theme.breakpoints.down('md')} {
    display: none;
  }
`;

Will be converted to pure css:
@media (max-width: 767.98px) {
  display: none;
}

Why subtract .02px? Browsers don’t currently support range context queries, so we work around the limitations of min- and max- prefixes and viewports with fractional widths (which can occur under certain conditions on high-dpi devices, for instance) by using values with higher precision.



Single breakpoint - only

There are also media queries and mixins for targeting a single segment of screen sizes using the minimum and maximum breakpoint widths.


Type declaration
  declare function only(
    name: string,
    orientation?: 'portrait' | 'landscape'
  ) => string
const Box = styled.div`
  background-color: pink;

  ${({ theme }) => theme.breakpoints.only('md')} {
    background-color: rebeccapurple;
  }
`;

Will be converted to pure css:
@media (min-width: 768px) and (max-width: 991.98px) {
  background-color: rebeccapurple;
}


Breakpoints range - between

Similarly, media queries may span multiple breakpoint widths.


Type declaration
 declare function between(
    min: string,
    max: string,
    orientation?: 'portrait' | 'landscape'
  ) => string
const Box = styled.div`
  background-color: gold;

  ${({ theme }) => theme.breakpoints.between('md', 'xl')} {
    background-color: rebeccapurple;
  }
`;

Will be converted to pure css:
@media (min-width: 768px) and (max-width: 1199.98px) {
  background-color: rebeccapurple;
}


useMediaQuery hook

features:

  • 🧐 optimal performance by dynamically monitoring document changes in media queries.
  • 💪🏻 It supports SSR (server-side rendering).
  • 📦 Minified and gzipped size 284b.

Type declaration
 declare function useMediaQuery(query: string) => boolean
import { useTheme } from 'styled-components'; // or from '@emotion/react'
import { useMediaQuery } from 'styled-breakpoints/use-media-query';
import { Box } from 'third-party-library';

const SomeComponent = () => {
  const { breakpoints } = useTheme();
  const isMd = useMediaQuery(breakpoints.only('md'));

  return <AnotherComponent>{isMd && <Box />}</AnotherComponent>;
};


License

MIT License

Copyright (c) 2018-2019 Maxim Alyoshin.

This project is licensed under the MIT License - see the LICENSE file for details.



Contributors

mg901
mg901

💬 💻 🎨 📖 💡 🚇 🚧 📆 📣 🔬 👀 ⚠️ 🔧
Abu Shamsutdinov
Abu Shamsutdinov

🐛 💻 💡 🤔 👀 📢
Sova
Sova

💻 💡 🤔 👀 📢
Jussi Kinnula
Jussi Kinnula

🐛 💻
Rafał Wyszomirski
Rafał Wyszomirski

📖
Adrian Celczyński
Adrian Celczyński

🐛 💻
Sam Holmes
Sam Holmes

💻 🤔
Ontopic
Ontopic

🤔
Ryan Bell
Ryan Bell

🤔
Bart Nagel
Bart Nagel

🐛 💻 💡 🤔
Greg McKelvey
Greg McKelvey

💻
Buck DeFore
Buck DeFore

🤔
Pierre Burel
Pierre Burel

🐛
Pawel Kochanek
Pawel Kochanek

🐛 💻
Ian Christopher B. de Jesus
Ian Christopher B. de Jesus

🐛
David de Lusenet
David de Lusenet

🐛 🤔
Dan Adler
Dan Adler

🐛

styled-breakpoints's People

Contributors

alexhtech avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar flagoon avatar gr34se avatar greenkeeper[bot] avatar iryanbell avatar jussikinnula avatar mckelveygreg avatar meme-content avatar mg901 avatar oowldev avatar rafauke avatar sdowding avatar semantic-release-bot avatar sergeysova avatar stuneak avatar tremby 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  avatar  avatar  avatar  avatar

styled-breakpoints's Issues

Custom breakpoints passed directly to core methods (up, down, between)

Important!

Leave your opinion on this topic in the issue :)

Problem

Many projects don't have dedicated UI/UX Designer to create views for all popular devices (mobile, desktop, tablet, etc.) and we are forced to tweak our designs with our own eye. Especially in the era of fold and tablet split screen when they can be even 280px wide.

Library provides almost full functionality we need to make our apps fully-responsive, but I find there is lack of the possibility to pass fully custom breakpoint by it's number.

In my projects I had to create very custom sliders with many @media-query adjustments.
Even to the point where one class had about 10 media queries.

I wish there was such possibility, because every project has it's own edge cases.

Creating very custom theme configuration object is one option, but it can lead to some other issues - for example naming.
I've seen projects with breakpoints called like small, smaller, smallest, small laptop because the solution they were using didn't provide a possibility to use custom breakpoint.

To my way of thinking - those weird names are way worse than using number number directly.

So I created PR which adds the possibility to provide number directly to the core methods of the library. I've tested it both with hooks and CSS-in-JS and it works 😅

Example

Note: it doesn't work with only method, because it wouldn't make any sense. It shows proper error instead :)

Here is a little demo of my implementation:
https://github.com/WiktorG/styled-custom-breakpoints-demo

import styled from "styled-components"

import { up, down, only, between } from 'styled-breakpoints'
import { useBreakpoint } from "styled-breakpoints/react-styled"

const Wrapper = styled.div`
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  flex-direction: column;
`

const Heading = styled.h1`
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  font-size: 12px;
  ${up(1011)} {
    font-size: 35px;
  }
`

export const useBreakpoints = () => {
  const isXs = useBreakpoint(down("xs"));
  const isSm = useBreakpoint(only("sm"));
  const isMd = useBreakpoint(only("md"));
  const isLg = useBreakpoint(only("lg"));
  const isXl = useBreakpoint(up("xl"));
  const isCustom = useBreakpoint(up(1200));
  const isCustomBetween = useBreakpoint(between(1000, 1200));

  return {
    isXs,
    isSm,
    isMd,
    isLg,
    isXl,
    isCustom,
    isCustomBetween
  };
};


function Test() {
  const { isXs, isSm, isMd, isLg, isXl, isCustom, isCustomBetween } = useBreakpoints();

  return (
  <ul>
    <li>isXs: {`${isXs}`}</li>
    <li>isSm: {`${isSm}`}</li>
    <li>isMd: {`${isMd}`}</li>
    <li>isLg: {`${isLg}`}</li>
    <li>isXl: {`${isXl}`}</li>
    <li>isCustom up 1200: {`${isCustom}`}</li>
    <li>isBetween 1000 & 1200: {`${isCustomBetween}`}</li>
  </ul>
  )
}

function App() {
  return (
    <Wrapper>
      <Heading>Hello from custom styled breakpoints</Heading>
      <Test />
    </Wrapper>
  );
}

export default App;

PR

Here is my pull request #1074 - the Readme is yet to be updated.

An in-range update of commitlint is breaking the build 🚨

There have been updates to the commitlint monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the commitlint group definition.

commitlint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 39 commits.

  • c17420d v8.1.0
  • ca19d70 chore: update dependency lodash to v4.17.14 (#724)
  • 5757ef2 build(deps): bump lodash.template from 4.4.0 to 4.5.0 (#721)
  • 5b5f855 build(deps): bump lodash.merge from 4.6.0 to 4.6.2 (#722)
  • 4cb979d build(deps): bump lodash from 4.17.11 to 4.17.13 (#723)
  • a89c1ba chore: add devcontainer setup
  • 9aa5709 chore: pin dependencies (#714)
  • c9ef5e2 chore: centralize typescript and jest setups (#710)
  • c9dcf1a chore: pin dependencies (#708)
  • 6a6a8b0 refactor: rewrite top level to typescript (#679)
  • 0fedbc0 chore: update dependency @types/jest to v24.0.15 (#694)
  • 0b9c7ed chore: update dependency typescript to v3.5.2 (#695)
  • 4efb34b chore: update dependency globby to v10 (#705)
  • 804af8b chore: update dependency lint-staged to v8.2.1 (#696)
  • 9075844 fix: add explicit dependency on chalk (#687)

There are 39 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

`xs: 0px` cannot be assigned as minimum breakpoint.

Then why is it in default Breakpoints if I can't write a regular piece of code

[up('xs')(props)]: { flexBasis: "calc(100% / 1)", },

[up('sm')(props)]: { flexBasis: "calc(100% / 2)", },

[up('md')(props)]: { flexBasis: "calc(100% / 3)", },

I don't want to write down('sm')

An in-range update of commitizen is breaking the build 🚨

The devDependency commitizen was updated from 4.0.1 to 4.0.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

commitizen is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v4.0.2

4.0.2 (2019-07-19)

Bug Fixes

  • deps: update dependency lodash to v4.17.15 (#652) (129a779)
Commits

The new version differs by 3 commits.

  • 129a779 fix(deps): update dependency lodash to v4.17.15 (#652)
  • 5f71dfe Adding tasks to publish test results to AzurePipelines (#590)
  • f5751b2 chore: update mocha, other dev deps (#653)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

useBreakpoint issues with SSR (eg Next.js)

I came across a bug in my project yesterday and I think have now traced it to styled-breakpoints.

I've made a minimal reproduction which you can find at https://github.com/tremby/next-mq-bug

The main branch has the broken case, which is also deployed at http://next-mq-bug-1.surge.sh/

In this reproduction, I initialize a variable mobile, then in a try/catch block I run the useBreakpoint hook. I have to run it in a try/catch because window does not exist during server-side rendering, and it's impossible to know how wide the user's browser window is. Without the try/catch block, an error would be thrown here: https://github.com/mg901/styled-breakpoints/blob/master/react-styled/index.js#L9

Whichever version of the display initialized mobile to the value matching the width of the viewport at load time, displays correctly. The other version displays incorrectly. The wrong styled-components classes have been added to the wrong elements. On resizing so that the media query flips, the version which displayed correctly still displays correctly. The version which started out wrong is still wrong.

Here are some screenshots.


After hitting refresh at a narrow width:

Screen Shot 2020-12-04 at 20 16 15


Without refresh, after then resizing to be wider:

Screen Shot 2020-12-04 at 20 16 25


After hitting refresh at that wider width:

Screen Shot 2020-12-04 at 20 16 29


And then after resizing to be narrower again without hitting refresh:

Screen Shot 2020-12-04 at 20 16 36


I then made my own implementation of useBreakpoint (albeit limited to a hard-coded media query) and I do not get the same bug. In my version I don't actually need the try/catch block either, since everything which tries to use window happens in useEffect, and effects don't run at SSR time. That version is on my "without-styled-breakpoints" branch, and is deployed here: http://next-mq-bug-2.surge.sh/

If you are open to a rewrite of your useBreakpoint function I could give it a shot. Or do you think the bug is actually elsewhere, like in styled-components or in Next.js?

Wrong type declaration for createTheme function

Hi, you have wrong type declaration for createTheme method. If you provide breakpoints into the method, but return them without spreading, the object will be:

{'styled-components': { breakpoints: {...some obj with breakpoints}}}

but type definition suggests:

{'styled-components': {...some obj with breakpoints}}

I's like to fix this, but tell me what is wrong? Type or the function? Changing the method would be a breaking change, so I'll start with changing type definition.

An in-range update of husky is breaking the build 🚨

The devDependency husky was updated from 2.4.1 to 2.5.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

husky is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/husky-2.5.0 at 100.0% (Details).

Commits

The new version differs by 15 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Can't use breakpoints as specified in the documentation

Using version 6.6.3, I'm trying to use styled-breakpoints as specified in the docs:

export const StyledDrawer = styled(Drawer)`
  && {
    ${down('tablet')} {
      color: lightcoral;
    }
  }
`;

And I'm getting this error :

Uncaught Error: [styled-breakpoints]: 'mobile' is invalid breakpoint name. Use 'keys, values, up, down, between, only'

I tried with different breakpoints (mobile, desktop), and I am still getting this error.

React 18

Hello,

Would it be possible to bump the react peer dep?

Thank you!

A possible bug (or a misunderstanding of the API)

I just started using this lib and I'm a little bit confused by the API. The docs give two examples with the md breakpoint and the up and down functions respectively. The first example seems clear to me: ${up('md')} translates to @media (min-width: 768px). But in the second example, ${down('md')} translates to @media (max-width: 991.98px) whereas I would have expected @media (max-width: 767.98px) (also see the screenshot below).
On a given viewport width of 800px, both useBreakpoint(up('md')) and useBreakpoint(down('md')) return true at the same time. Maybe I'm understanding the API wrong, but shouldn't they be mutually exclusive? I'd expect the latter to be false.
Merry Christmas and thank you in advance for your help 🙏

image

styled-breakpoints 8.0.0 build is broken

After upgrading styled-breakpoints to newest version, the build seems to refer to types.d which cannot be found in dist.

1:103 Cannot find module './types.d'.
  > 1 | import { GetFn, MakeErrorMessage, Options, StyledBreakpoints, MediaQueries, Orientation, Props } from './types.d';
      |                                                                                                       ^
    2 | export { Options, StyledBreakpoints, MediaQueries, Orientation, Props };
    3 | export declare const _type: (x: unknown) => string;
    4 | export declare const _get: GetFn;```

An in-range update of commitizen is breaking the build 🚨

The devDependency commitizen was updated from 4.0.2 to 4.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

commitizen is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v4.0.3

4.0.3 (2019-07-20)

Bug Fixes

  • deps: update dependency cz-conventional-changelog to v3 (#654) (2a1a111)
  • bump tests to release (#656) (270cb5c)
Commits

The new version differs by 2 commits.

  • 270cb5c fix: bump tests to release (#656)
  • 2a1a111 fix(deps): update dependency cz-conventional-changelog to v3 (#654)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of eslint-plugin-jest is breaking the build 🚨

The devDependency eslint-plugin-jest was updated from 22.9.0 to 22.10.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v22.10.0

22.10.0 (2019-07-17)

Features

Commits

The new version differs by 7 commits.

  • 28bd1dc feat(rules): adds no-if rule (#293)
  • 7ebdc0e chore: enforce import destructure order
  • 31c7cef chore: convert to import/export (#302)
  • 9f858cb chore: delete tests instead of ignoring them with babel
  • c595ba0 chore: do not include tests in published tarball
  • 4b4eb78 chore: fix lint error in md file
  • d3ea720 chore(docs): fix typo (#304)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didn’t receive a CI status on the greenkeeper/initial branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.

Additional range selectors

Conceptually, I like to think of a breakpoint as a threshold value. If the breakpoint value is 500px I would expect an above query to be >500px and a below query to be <500px.

In the example:

{
  sm: '576px',
  md: '768px',
  lg: '992px',
  xl: '1200px',
}

up('md') => '@media (min-width: 768px) { ... }'
only('md') => '@media (min-width: 768px) and (max-width: 991.98px) { ... }'
down('md') => '@media (max-width: 991.98px) { ... }'
between('md', 'lg') => '@media (min-width: 768px) and (max-width: 1199.98px) { ... }'

up('md') makes complete sense as being greater than or equal to md.

only('md') also makes total sense as selecting [md, lg).

down('md') I don't agree with, as it seems like it should be <md. Instead, it is <lg.

between('md', 'lg') follows this same logic as down, querying from [md, xl), when I would prefer[md, lg)

As this is currently written, there is no way to select down() from the lowest breakpoint, which is often the most useful breakpoint, as things are most likely to break the layout at this extreme value. down('xs') is currently interpreted as <Sm (not <Xs).


Proposed solution:

The names for this new query could be downFrom or upTo.

downFrom('md') => '@media (max-width: 767.8px) { ... }'
upTo('md') => '@media (max-width: 767.8px) { ... }'

Alternatively, down('md', orientation, true) could use a third argument to specify the max-width of md rather than the next higher breakpoint (lg). Renaming calcMinWidth -> getWidthAtBreakpoint and calcMaxWidth -> getWidthAtNextBreakpoint also helps to clarify the functionality.

Here's a feature proposal of how the latter could look with 3 additional unit tests: https://github.com/iRyanBell/styled-breakpoints/tree/feat/is-below-break-proposal

Hook API: useBreakpoint

I propose a hooks API:

import { up, useBreakpoint } from 'styled-breakpoints`

const isMobile = useBreakpoint(up('tablet'));

Working Implementation:

import { useState, useEffect } from 'react';
import { useTheme } from 'styled-components';

export const useBreakpoint = (breakpoint: (z: { theme: any }) => string) => {
  const theme = useTheme();
  const query = breakpoint({ theme }).replace(/^@media/, '');

  const mq = window.matchMedia(query);
  const [isBreak, setIsBreak] = useState(mq.matches);

  useEffect(() => {
    function handleResize() {
      setIsBreak(window.matchMedia(query).matches);
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return isBreak;
};

export default useBreakpoint;

useBreakpoint is not using the breakpoints defined in theme

Hi @mg901 thanks for this awesome library.

I'm using this library in one of my project and wanted to use breakpoint with useBreakpoint so that i can render my components conditionality based on the screen size. But even when i defined theme with createTheme it seems to take value from default breakpoints.

CodeSandbox Link:- https://codesandbox.io/s/hooks-api-emotion-forked-3glb0s

After going through the code i understood that in this case theme is not getting attached to function automatically as it would in case of rendering it as styled/react component.

Solution i am thinking of :-

  • Exposing createUseBreakpoint through which we can define the theme object to be used in case, and instead of default theme it will use the theme we are passing here.

Let me know your thoughts ?

feature request: exclude invalid breakpoints instead of failing

I've encountered an issue where styled-breakpoints is incompatible with latest Material UI and styled-components because MUI merges its theme into the styled theme provider, including helper functions into the breakpoints key. A description of how MUI suggests working with themes for both is here: mui/material-ui#28979 (comment)

When setting up providers this way and using styled-breakpoints in a component, such as:

import { up } from 'styled-components'

const Foo = styled.div`
  ${up('sm')} {
    width: 100%;
  } 
`

The following error occurs:

Uncaught Error: [styled-breakpoints]: Check your theme. `keys: xs,sm,md,lg,xl, values: [object Object], up: function up(key) {
    var value = typeof values[key] === 'number' ? values[key] : key;
    return "@media (min-width:".concat(value).concat(unit, ")");
  }, down: function down(key) {
    var value = typeof values[key] === 'number' ? values[key] : key;
    return "@media (max-width:".concat(value - step / 100).concat(unit, ")");
  }, between: function between(start, end) {
    var endIndex = keys.indexOf(end);
    return "@media (min-width:".concat(typeof values[start] === 'number' ? values[start] : start).concat(unit, ") and ") + "(max-width:".concat((endIndex !== -1 && typeof values[keys[endIndex]] === 'number' ? values[keys[endIndex]] : end) - step / 100).concat(unit, ")");
  }, only: function only(key) {
    if (keys.indexOf(key) + 1 < keys.length) {
      return between(key, keys[keys.indexOf(key) + 1]);
    }

    return up(key);
  }, not: function not(key) {
    // handle first and last key separately, for better readability
    var keyIndex = keys.indexOf(key);

    if (keyIndex === 0) {
      return up(keys[1]);
    }

    if (keyIndex === keys.length - 1) {
      return down(keys[keyIndex]);
    }

    return between(key, keys[keys.indexOf(key) + 1]).replace('@media', '@media not all and');
  }, unit: px,` are invalid breakpoints. Use only pixels.

Note the last line about invalid breakpoints. The large output here is MUI's up helper, which styled-breakpoints accurately determines is not a valid breakpoint declaration.

This could be mitigated if the checkAllValuesHasPixels were changed to a getValidBreakpoints that filters out invalid ones determined by the check for px and proceeds with the ones that are valid instead of creating an invariant and failing. Related code: https://github.com/mg901/styled-breakpoints/blob/master/styled-breakpoints/styled-breakpoints.js#L49

Another option is to expose createStyledBreakpoints from the export on the public package so that pathToMediaQueries could be overridden, but the friendly path is to be resilient when faced with a mix of valid and invalid options.

An in-range update of eslint-plugin-jest is breaking the build 🚨

The devDependency eslint-plugin-jest was updated from 22.11.1 to 22.12.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v22.12.0

22.12.0 (2019-07-20)

Features

Commits

The new version differs by 1 commits.

  • 7ae98f5 feat: assert that async expects are awaited or returned (#255)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Types are incorrect and/or missing

First of all, thanks for maintaining this library! One of the few that hasn't been left for death.

However, I've been running into some issues when using this package in a TypeScript project.

First of all, the up/down/between/only function parameter is not strictly typed. It would be nice if the keys from the createTheme object would be used here. Now this parameter is just of type string. However, I can still use the package fine without this strict typing.

Another thing which is causing a bigger issue: the return value of the up/down/between/only functions. At the moment that is any, which causes an error when using these functions in combination with useBreakpoint:

const isDesktop = useBreakpoint(up("lg"));

// The following ESLint error is being thrown:
// Unsafe argument of type `any` assigned to a parameter of type `Function`.

Let me know if you need any more information!

`xs: 0px` cannot be assigned as minimum breakpoint

Hi guys !

In a NextJs project, I use your library for handling easily breakpoints (thanks by the way).

Unfortunately, this code below seems does not work since this following error has triggered :
Error: [styled-breakpoints]: 'xs: 0px' cannot be assigned as minimum breakpoint.

FYI, I use default breakpoint values.

export const Container = styled.div<WrapperProps>`
  ${space}

  margin-left: auto;
  margin-right: auto;

  ${between('xs', 'md')} {
    width: 90%;
  }

  ${up('md')} {
    width: 70%;
  }
`;

I remember a few months ago, this kind of code worked.

I use next 12.0.7 (which uses SWC instead of Babel now), styled-components 5.3.3 and styled-breakpoints 10.2.1.

Thanks for your help :-).

An in-range update of eslint-plugin-flowtype is breaking the build 🚨

The devDependency eslint-plugin-flowtype was updated from 3.9.0 to 3.9.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-flowtype is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v3.9.1

3.9.1 (2019-05-23)

Bug Fixes

Commits

The new version differs by 1 commits.

  • 712d840 fix: requireReadOnlyReactProps (#406)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Add React 17.x to peerDependencies

Hi,

When will React 17.x be added as peerDeependency?
When you have React 17.x and npm version 7 installed you need to install this pacakge with --force or --legacy-peer-deps flags, otherwise you get:

npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!   peer react@">=16.8.0" from @emotion/[email protected]
npm ERR!   node_modules/@emotion/react
npm ERR!     peerOptional @emotion/react@"^11.0.0" from [email protected]
npm ERR!     node_modules/styled-breakpoints
npm ERR!       styled-breakpoints@"*" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peerOptional react@"^16.8.0" from [email protected]
npm ERR! node_modules/styled-breakpoints
npm ERR!   styled-breakpoints@"*" from the root project

Thanks!

Does not accept custom breakpoints as ems

We all now, that relay just on pixels is not enough, so I tried to have breakpoints based on em values, but some how converts these em values to new ems:

I am using:
"next": "^8.0.0",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"styled-breakpoints": "^6.6.2",
"styled-components": "^4.1.3",
"styled-normalize": "^8.0.6",
"styled-theme": "^0.3.3"

const theme = {
  breakpoints:{
      xs: '30em',
      sm: '50em',
      md: '60em',
      lg: '80em',
      xl: '120em',
  }
}
const Container = styled.div`
  ${down('md')} {
    color: rebeccapurple;
  }
`

This is what I got SSR rendered:

/* sc-component-id: PageTitle__Container-c1sqxi-0 */
 @media (min-width:48em) and (max-width:61.99875em){
   .bsEiBw{color:rebeccapurple;}
 }
 @media (min-width:1.875em) and (max-width:3.12375em){
   .jQjQlc{color:rebeccapurple;}
 }
 @media (min-width:3.125em) and (max-width:3.74875em){
   .bBciUM{color:rebeccapurple;}
 }
 @media (max-width:2.62375em){
   .haykbX{color:rebeccapurple;}
 }
 @media (max-width:47.99875em){
   .imXVfl{color:rebeccapurple;}
 }
 @media (max-width:4.99875em){
   .bANXey{color:rebeccapurple;}
 }
 @media (max-width:4.99875em){
   .gZDZUq{color:rebeccapurple;}
 }
 @media (max-width:4.99875em){
   .pTrKY{color:rebeccapurple;}
 }

If I use px as breakpoint values, then all is working as expected.

Current element has class gZDZUq

Queries in emotion css blocks have broken types

Hi Maxim!

First of all: many thanks for such a great library :)

I am writing as I have stumbled upon a potential bug that relates to Typescript.

the following line of code will result in a Type Error

import { css } from "@emotion/react";
import { down } from "styled-breakpoints";

const myReusableCss = css`
  ${down("xs")}{
    background: red;
  }
`

you can check the reproduction in a Code Sandbox:

https://codesandbox.io/s/stupefied-hertz-0z2b6?file=/src/MyComponent.ts

I might take a deeper look into code later on in the week to see whether I could come up with a solution.

Override default breakpoints globally

Many thanks for this package, I just started to use it in a project and it's very similar to what I have used for SCSS in the past.

One thing I didn't find is that is there a way to override the default breakpoints, globally? In the readme as I see overriding can be done with createTheme and ThemeProvider.

Fortunately the project uses the same breakpoints as the defaults so it's not a big issue right now, but later a global customization may be needed.

rules-of-hooks warning after update to v11.0.2

Hi @mg901,

first of all, I really like the changes introduced in v11 today. Working with the down-function feels a lot more natural now. However, I noticed that after the update to v11.0.2, the useBreakpoint hook now triggers a rules-of-hooks warning.

Example: useBreakpoint(up('md'))
Output: Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks

seems not to work with astroturf

in Astroturf all the variables have to be statically analyzable and be in the same file. examples from readme fail with the message saying that

Could not resolve interpolation to a value, css returned class name, or styled component. All interpolated styled components must be in the same file and values must be statically determinable at compile time.
  13 |   }
  14 |
> 15 |   ${up('tablet')} {

typescript support

I tried to find typings for the library and unfortunately have not found anything... Do you have plans to develop them?

Naming and functionality of below function

The below function now uses the next breakpoint instead of the current.

Is this intended? Because when writing below('tablet') I would thing to receive a media query that specifies < 768px. Now it uses the next breakpoint and gives you < 992px (desktop)

See pull request: #6

An in-range update of eslint-plugin-jest is breaking the build 🚨

The devDependency eslint-plugin-jest was updated from 22.13.2 to 22.13.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/eslint-plugin-jest-22.13.3 at 100.0% (Details).

Release Notes for v22.13.3

22.13.3 (2019-07-22)

Bug Fixes

  • import TS utils from correct package (7f1867b)
Commits

The new version differs by 1 commits.

  • 7f1867b fix: import TS utils from correct package

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of eslint-plugin-import is breaking the build 🚨

The devDependency eslint-plugin-import was updated from 2.18.1 to 2.18.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

eslint-plugin-import is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).
  • coverage/coveralls: First build on greenkeeper/eslint-plugin-import-2.18.2 at 100.0% (Details).

Commits

The new version differs by 4 commits.

  • 1a90a20 Bump to v2.18.2
  • b3e5311 bump utils to v2.4.1
  • 984fa3b Remove duplicate no-duplicates changelog entry
  • 582236b [bugfix] Skip warning on type interfaces

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Is this a bug ?

I'm trying to reproduce
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575.98px)

it should work with ${down('sm')} due to expecting convert into down('sm') => '@media (max-width: 576px) { ... }'

And taking a look into your docs, I couldn't find a solution without breaking the rules....

Break-points
// {
// xs: '0px',
// sm: '576px',
// md: '768px',
// lg: '992px',
// xl: '1200px',
// }

Docs
/**

  • @return {string} media query
    down('md') => '@media (max-width: 991.98px) { ... }'
    */

Library not working with react-native-web

Hey team,

First of all thanks for this awesome tool. Secondly, I'm facing an issue with my react-native-web project which uses styled-components where none of my responsive styles get applied to the dom elements:

Here's my component definition:

import styled from 'styled-components/native';

import { up, down, between } from 'styled-breakpoints';

export const H3Headline = styled.Text`
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
  color: white;

  ${down('sm')} {
    background-color: red;
    font-size: 32px;
    line-height: 40px;
    font-weight: 700;
  }

  ${between('sm', 'lg')} {
    background-color: blue;
    font-size: 32px;
    line-height: 40px;
    font-weight: 700;
  }

  ${up('lg')} {
    background-color: yellow;
    font-size: 48px;
    line-height: 60px;
    font-weight: 700;
  }
`;

As you can see, I'm importing styled from styled-components/native and my component is a react native's Text component. And this is what I'm seeing on the DOM:

image

If I replace my styled-components' import and the component to something like:

import styled from 'styled-components';

import { up, down, between } from 'styled-breakpoints';

export const H3Headline = styled.span`
  ... this is the same code I had before

The DOM output is the expected one and the responsiveness works perfectly:

image

I'm not sure if I have to do something extra for making this awesome tool with react-native-web or if there is no way of making it work.

Thanks,

Eric.

Proposal: Add example of usage with object notation

Hey hello,

Thanks for the library, it is really useful 👍 I would like to propose to document usage of styled-breakpoints when using object notation in order to explain that breakpoint functions (up, down etc.) are curried and that props have to be passed explicitly:

const MyComponent = styled('div')(props => ({
  color: props.theme.colors.primary,
  fontSize: '1.5rem',
  [up('sm')(props)]: {
    fontSize: '1rem'
  }
}))

By props I mean an object with a compatible "interface" i.e. containing a theme property.

I can create a PR for that if that's ok.

Cheers!

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.