React component breakpoints

![Verify](https://github.com/LeeCheneler/react-component-breakpoints/workflows/Verify/badge.svg) <img style="display: inline-block; margin-right: 5px;" src="https://badgen.net/github/release/LeeCheneler/react-component-breakpoints" />

Version: 1.0.1 Updated: 05/25/2020

By: leecheneler License: MIT

Downloads Last 30 Days: 1

react-component-breakpoints

Verify

React to component level breakpoints.

Why

Utilising the useBreakpoints React hook allows you to build components that can respond to their own width rather than the page's width.

Installing

yarn add react-component-breakpoints

Getting started

A simple example of a component reacting to its size changes.

import { useBreakpoints } from "react-component-breakpoints";

const Example = () => {
  const [ref, br, [wide, widest]] = useBreakpoints(500, 900);

  const breakpointValue = br("default", "wide", "widest");
  return (
    <div ref={ref}>
      <p>Breakpoint value: {breakpointValue}</p>
      <p>Wide: {wide.toString()}</p>
      <p>Widest: {widest.toString()}</p>
    </div>
  );
};

API

useBreakpoints

const [ref, br, [hit]] = useBreakpoints(...breakpoints);

Takes breakpoint numbers (...breakpoints) as arguments.

Returns an array with:

  • A React Ref (ref) to pass to a JSX element to measure.

  • A function (br) that returns the corresponding value according to the current breakpoint, the first argument is the default value if no breakoint is hit.

  • An array of booleans ([hit]) indicating which breakpoints have been hit. The number of booleans in the array always matches the number of breakpoints you gave.

Categories: React js