}
```
--------------------------------
### Server-Side Rendering with React Context
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Demonstrates how to use react-responsive in a server-side rendering context by providing a mock responsive context value. This allows rendering components with specific device characteristics on the server.
```jsx
import { Context as ResponsiveContext } from 'react-responsive'
import { renderToString } from 'react-dom/server'
import App from './App'
...
// Context is just a regular React Context component, it accepts a `value` prop to be passed to consuming components
const mobileApp = renderToString(
)
...
```
--------------------------------
### Creating Combined Responsive Media Queries with Hooks
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Demonstrates a DRY (Don't Repeat Yourself) approach to creating combined responsive media queries using custom hooks. This pattern abstracts complex query logic for easier reuse.
```javascript
import { useMediaQuery } from 'react-responsive'
const useDesktopMediaQuery = () =>
useMediaQuery({ query: '(min-width: 1280px)' })
const useTabletAndBelowMediaQuery = () =>
useMediaQuery({ query: '(max-width: 1279px)' })
const Desktop = ({ children }) => {
const isDesktop = useDesktopMediaQuery()
return isDesktop ? children : null
}
const TabletAndBelow = ({ children }) => {
const isTabletAndBelow = useTabletAndBelowMediaQuery()
return isTabletAndBelow ? children : null
}
```
--------------------------------
### Testing Responsive Components with React Context
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Illustrates how to test components that rely on react-responsive by providing different context values for mobile and desktop breakpoints. This ensures components render correctly across various screen sizes.
```jsx
import { Context as ResponsiveContext } from 'react-responsive'
import { render } from '@testing-library/react'
import ProductsListing from './ProductsListing'
describe('ProductsListing', () => {
test('matches the snapshot', () => {
const { container: mobile } = render(
)
expect(mobile).toMatchSnapshot()
const { container: desktop } = render(
)
expect(desktop).toMatchSnapshot()
})
})
```
--------------------------------
### Using Shorthand Properties with useMediaQuery in React
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Shows how to utilize shorthand camel-cased properties with the `useMediaQuery` hook for constructing media queries more idiomatically in React. This simplifies the syntax for common media query conditions.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const Example = () => {
const isDesktopOrLaptop = useMediaQuery({ minWidth: 1224 })
const isBigScreen = useMediaQuery({ minWidth: 1824 })
const isTabletOrMobile = useMediaQuery({ maxWidth: 1224 })
const isPortrait = useMediaQuery({ orientation: 'portrait' })
const isRetina = useMediaQuery({ minResolution: '2dppx' })
return
...
}
```
--------------------------------
### Handling Media Query Changes with useMediaQuery Hook
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Demonstrates how to use the `useMediaQuery` hook from react-responsive to track changes in media query matches. It includes a callback function that is executed whenever the media query's state changes.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const Example = () => {
const handleMediaQueryChange = (matches) => {
// matches will be true or false based on the value for the media query
}
const isDesktopOrLaptop = useMediaQuery(
{ minWidth: 1224 },
undefined,
handleMediaQueryChange
)
return
...
}
```
--------------------------------
### Responsive Design with useMediaQuery Hooks in React
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Demonstrates how to use the `useMediaQuery` hook from react-responsive to conditionally render components based on various media query conditions like screen size and orientation. This approach is suitable for functional components.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const Example = () => {
const isDesktopOrLaptop = useMediaQuery({
query: '(min-width: 1224px)'
})
const isBigScreen = useMediaQuery({ query: '(min-width: 1824px)' })
const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' })
const isPortrait = useMediaQuery({ query: '(orientation: portrait)' })
const isRetina = useMediaQuery({ query: '(min-resolution: 2dppx)' })
return (
Device Test!
{isDesktopOrLaptop &&
You are a desktop or laptop
}
{isBigScreen &&
You have a huge screen
}
{isTabletOrMobile &&
You are a tablet or mobile phone
}
Your are in {isPortrait ? 'portrait' : 'landscape'} orientation
{isRetina &&
You are retina
}
)
}
```
--------------------------------
### Testing Responsive Components with Context in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
The `Context` component is also valuable for testing responsive React components. By wrapping your component under test with `ResponsiveContext.Provider`, you can inject specific device characteristics (like width or resolution) into the test environment. This allows for predictable and reproducible test results, ensuring your responsive logic behaves as expected across different simulated devices.
```jsx
import React from 'react'
import { Context as ResponsiveContext } from 'react-responsive'
import { render } from '@testing-library/react'
// Component under test
const ProductsListing = () => {
const isMobile = useMediaQuery({ maxWidth: 767 })
return (
Product 1
Product 2
Product 3
)
}
// Tests
describe('ProductsListing', () => {
test('renders single column on mobile', () => {
const { container } = render(
)
expect(container.querySelector('.grid-1-col')).toBeTruthy()
})
test('renders three columns on desktop', () => {
const { container } = render(
)
expect(container.querySelector('.grid-3-col')).toBeTruthy()
})
})
```
--------------------------------
### Responsive Design with MediaQuery Components in React
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Illustrates how to use the `MediaQuery` component from react-responsive for conditional rendering based on media queries. This method is useful for wrapping content that should only be displayed under specific conditions. It also shows the use of render props.
```jsx
import MediaQuery from 'react-responsive'
const Example = () => (
Device Test!
You are a desktop or laptop
You also have a huge screen
{/* You can also use a function (render prop) as a child */}
{(matches) =>
matches ?
You are retina
:
You are not retina
}
)
```
--------------------------------
### Forcing Device Settings with useMediaQuery in React
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Demonstrates how to override automatically detected device settings using the `device` prop with the `useMediaQuery` hook. This is particularly useful for server-side rendering (SSR) or testing purposes in a Node.js environment.
```jsx
import { useMediaQuery } from 'react-responsive'
const Example = () => {
const isDesktopOrLaptop = useMediaQuery(
{ minDeviceWidth: 1224 },
{ deviceWidth: 1600 } // `device` prop
)
return (
{isDesktopOrLaptop && (
this will always get rendered even if device is shorter than 1224px,
that's because we overrode device settings with 'deviceWidth: 1600'.
)}
)
}
```
--------------------------------
### Server-Side Rendering with Context in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
The `Context` component from `react-responsive` is crucial for server-side rendering (SSR). It provides device-specific values to all `useMediaQuery` hooks within the component tree, bypassing the limitations of `window.matchMedia` which is unavailable on the server. This ensures that your components render correctly based on expected device characteristics during SSR.
```jsx
import React from 'react'
import { Context as ResponsiveContext, useMediaQuery } from 'react-responsive'
import { renderToString } from 'react-dom/server'
// Child component uses the hook normally
const Header = () => {
const isMobile = useMediaQuery({ maxWidth: 767 })
return (
{isMobile ? : }
)
}
const MobileNav = () =>
const DesktopNav = () =>
// Server-side rendering
const serverRender = (deviceWidth) => {
return renderToString(
)
}
// Render mobile version
const mobileHTML = serverRender(375) // iPhone width
// Render desktop version
const desktopHTML = serverRender(1440) // Desktop width
```
--------------------------------
### Create Reusable Breakpoint Components with React Responsive
Source: https://context7.com/yocontra/react-responsive/llms.txt
This snippet demonstrates how to create reusable React components (Desktop, Tablet, Mobile, Default) that conditionally render children based on screen size using the `useMediaQuery` hook from React Responsive. These components encapsulate design system rules for responsive UIs.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
// Reusable breakpoint components
const Desktop = ({ children }) => {
const isDesktop = useMediaQuery({ minWidth: 992 })
return isDesktop ? children : null
}
const Tablet = ({ children }) => {
const isTablet = useMediaQuery({ minWidth: 768, maxWidth: 991 })
return isTablet ? children : null
}
const Mobile = ({ children }) => {
const isMobile = useMediaQuery({ maxWidth: 767 })
return isMobile ? children : null
}
const Default = ({ children }) => {
const isNotMobile = useMediaQuery({ minWidth: 768 })
return isNotMobile ? children : null
}
// Usage in application
const App = () => (
)
```
--------------------------------
### Use onChange Callback with useMediaQuery in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
Shows how to utilize the third parameter of `useMediaQuery`, an `onChange` callback function. This callback is invoked whenever the media query match state changes, enabling developers to trigger side effects or update UI dynamically in response to viewport modifications. The callback receives a boolean indicating the new match state.
```jsx
import React, { useState } from 'react'
import { useMediaQuery } from 'react-responsive'
const ResponsiveWithCallback = () => {
const [layoutMode, setLayoutMode] = useState('desktop')
const handleMediaQueryChange = (matches) => {
// matches is true when viewport is >= 1224px
setLayoutMode(matches ? 'desktop' : 'mobile')
console.log(`Layout switched to: ${matches ? 'desktop' : 'mobile'}`)
}
const isDesktop = useMediaQuery(
{ minWidth: 1224 },
undefined, // no device override
handleMediaQueryChange
)
return (
Current layout mode: {layoutMode}
isDesktop: {isDesktop.toString()}
)
}
```
--------------------------------
### Override Device Characteristics with useMediaQuery in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
Illustrates how to use the second parameter of `useMediaQuery` to force specific device characteristics. This is particularly useful for server-side rendering (SSR) or testing environments where `window.matchMedia` might not be available or accurate. The `device` prop takes precedence over detected values.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const SSRComponent = () => {
// Force device width to 1600px regardless of actual viewport
const isDesktopOrLaptop = useMediaQuery(
{ minDeviceWidth: 1224 },
{ deviceWidth: 1600 }
)
// Override multiple device properties
const isLandscapeTablet = useMediaQuery(
{ minWidth: 768, maxWidth: 1024 },
{ width: 800, orientation: 'landscape' }
)
return (
{isDesktopOrLaptop && (
Rendered as desktop (device width forced to 1600px)
)}
{isLandscapeTablet && (
Rendered as landscape tablet
)}
)
}
```
--------------------------------
### Use useMediaQuery Hook for Responsive Design in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
Demonstrates the primary `useMediaQuery` hook for detecting media query matches. It accepts CSS media query strings or object properties and returns a boolean indicating if the current viewport matches the query. Supports various device characteristics like width, orientation, and resolution.
```jsx
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const ResponsiveComponent = () => {
// Using CSS media query string
const isDesktopOrLaptop = useMediaQuery({
query: '(min-width: 1224px)'
})
// Using object properties (numbers auto-convert to px)
const isBigScreen = useMediaQuery({ minWidth: 1824 })
const isTabletOrMobile = useMediaQuery({ maxWidth: 1224 })
const isPortrait = useMediaQuery({ orientation: 'portrait' })
const isRetina = useMediaQuery({ minResolution: '2dppx' })
return (
Device Test!
{isDesktopOrLaptop &&
You are a desktop or laptop
}
{isBigScreen &&
You have a huge screen
}
{isTabletOrMobile &&
You are a tablet or mobile phone
}
Your orientation is {isPortrait ? 'portrait' : 'landscape'}
{isRetina &&
You have a retina display
}
)
}
```
--------------------------------
### Converting Media Query Objects to Strings with toQuery
Source: https://context7.com/yocontra/react-responsive/llms.txt
The `toQuery` utility function from `react-responsive` converts an object containing media query properties into a standard CSS media query string. This function is particularly useful for debugging media queries or when you need to generate the raw query string for use in other contexts. It handles various properties like `minWidth`, `maxWidth`, `orientation`, and `screen`.
```javascript
import { toQuery } from 'react-responsive'
// Convert object properties to CSS media query string
const desktopQuery = toQuery({ minWidth: 1224 })
// Result: "(min-width: 1224px)"
const complexQuery = toQuery({
minWidth: 768,
maxWidth: 1024,
orientation: 'portrait'
})
// Result: "(min-width: 768px) and (max-width: 1024px) and (orientation: portrait)"
const retinaQuery = toQuery({ minResolution: '2dppx' })
// Result: "(min-resolution: 2dppx)"
const screenQuery = toQuery({ screen: true, minWidth: 1200 })
// Result: "screen and (min-width: 1200px)"
console.log('Desktop query:', desktopQuery)
console.log('Complex query:', complexQuery)
```
--------------------------------
### Disable Server-Side Rendering with Next.js
Source: https://github.com/yocontra/react-responsive/blob/master/README.md
Shows how to disable server-side rendering for react-responsive components when using Next.js. This is achieved by using dynamic imports with the `ssr: false` option.
```javascript
import dynamic from 'next/dynamic'
const MediaQuery = dynamic(() => import('react-responsive'), {
ssr: false
})
```
--------------------------------
### MediaQuery Component with onChange Callback in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
The MediaQuery component includes an `onChange` prop that triggers a callback function whenever the media query's match state changes. This allows for executing side effects in response to media query changes without the need for hooks, making it useful for managing state or performing actions when the viewport size or other media features change.
```jsx
import React, { useState } from 'react'
import MediaQuery from 'react-responsive'
const ComponentWithCallback = () => {
const [viewportInfo, setViewportInfo] = useState('')
const handleDesktopChange = (matches) => {
setViewportInfo(matches ? 'Desktop viewport detected' : 'Mobile viewport detected')
}
return (
Status: {viewportInfo}
Desktop Content
This only renders on desktop
)
}
```
--------------------------------
### Declarative Media Query Component in React
Source: https://context7.com/yocontra/react-responsive/llms.txt
The MediaQuery component provides a declarative, component-based approach to media queries in React. It renders its children only when the specified media query matches. This component supports all media query properties available in the hook and offers a render prop pattern for conditional rendering logic.
```jsx
import React from 'react'
import MediaQuery from 'react-responsive'
const ComponentBasedExample = () => (
Device Test!
{/* Simple conditional rendering */}
You are a desktop or laptop
You also have a huge screen
{/* Using query string */}
You are a tablet or mobile
{/* Render prop pattern for both match states */}
{(matches) =>
matches
?
You have a retina display
:
You have a standard display
}
)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.