Skip to content

useBreakpoint

React hook that enables access to Workbench breakpoints within Javascript.
  • The useBreakpoint hook is used for conditionally rendering markup based on the size of the viewport
  • Components will unmount when conditionally rendering like this, which will drop focus on an element and could potentially disrupt a user’s workflow if the viewport is resized
  • This may be heavy-handed for most cases; consider using responsive props instead
  • Note: useBreakpoint requires WorkbenchProvider
import { useBreakpoint } from '@gusto/workbench';
const Example = () => {
const md = useBreakpoint('md');
return (
<>
{md ? (
<span>I am visible on screens larger than "md"</span>
) : (
<span>I am displayed on "md" and below</span>
)}
</>
);
};

The following testing snippet(s) offer suggestions for testing the component using React Testing Library with occasional help from Jest.

// By default, React Testing Library will assume the smallest screen size possible.
// You need to use jest.mock to override the behavior of useBreakpoint
// At the top of the file after imports
// Use a mock like this if you want to be able to override the value on the fly in your specs
const mockUseBreakpointReturnValue = jest.fn();
jest.mock('@gusto/workbench', () => ({
__esModule: true,
...jest.requireActual('@gusto/workbench'),
// can also replace mockUseBreakpointReturnValue() with
// true or false to always return "true" or "false"
useBreakpoint: () => mockUseBreakpointReturnValue(),
}));
// Alternatively
jest.mock('@gusto/workbench', () => ({
__esModule: true,
...jest.requireActual('@gusto/workbench'),
useBreakpoint: breakpoint => {
// This is just an example of how you could update the
// behavior of the mock based on the value of the breakpoint
if (breakpoint === 'sm') return true;
else return false;
},
}));
it('some test', () => {
mockUseBreakpointReturnValue.mockReturnValue(true);
// or
mockUseBreakpointReturnValue.mockReturnValue(false);
render();
// make assertions
});
// Feel free to check out https://jestjs.io/docs/mock-functions for more info