Show a mobile navigation menu on small screens and a sidebar on wide screens using a simple hook inside your React component.
Fix server-side rendering issues where media queries fail because there is no browser, pass fake device settings to get correct output.
Run a function every time the user resizes their browser past a breakpoint using the onChange callback.
react-responsive is a TypeScript library for React that lets you apply CSS media queries directly inside your components. Instead of writing responsive rules in a stylesheet, you describe conditions like screen width or orientation in JavaScript and React handles showing or hiding content based on whether those conditions are met on the current device. There are two ways to use it. The first is a hook called useMediaQuery, which you call inside a function component. You pass in a query object describing the screen condition you want to check, and it returns true or false. The second is a component called MediaQuery that wraps content and only renders its children when the query matches. Both approaches support the same set of conditions: minimum and maximum widths, screen orientation, pixel density, and more. A useful feature for server-side rendering and testing is the ability to force a fake device configuration. When a page renders on a server, there is no real browser to detect screen size, which would normally cause the queries to fail or produce incorrect output. By passing in a device object with fixed values, you can tell the library to treat the environment as if it were a specific screen size. This can be provided per component or through a React context that applies to an entire component tree. The library also supports an onChange callback, so you can run a function whenever a media query result changes, for example when a user resizes their browser window. This makes it straightforward to trigger side effects based on layout changes. Installation is via npm. The README includes working code examples for all major use cases, including a pattern for defining reusable breakpoint components for desktop, tablet, and mobile, as well as Next.js-specific guidance for disabling server-side rendering on components that use the library.
← yocontra on gitmyhub — every repo by this author, as a profile.
Verify against the repo before relying on details.