I recently had the need to create a responsive sidebar in React that appears differently on large screens compared to smaller screens. In order to achieve this, I wanted to find a way to detect changes in responsive layouts in JSX.
To accomplish this, you can use the react-responsive package.
First, install the package using npm:
npm install react-responsive
Then, import the useMediaQuery
hook into your components:
import { useMediaQuery } from 'react-responsive';
You can use the useMediaQuery
hook like this:
const isBigScreen = useMediaQuery({ query: '(min-device-width: 1224px)' });
const isSmallScreen = useMediaQuery({ query: '(max-width: 1224px)' });
This example demonstrates the usage of breakpoints provided on the component’s home page, and they worked perfectly for my requirements.
I implemented this in a layout component like this:
import { useMediaQuery } from 'react-responsive';
export default function Layout({ children }) {
const isBigScreen = useMediaQuery({ query: '(min-device-width: 1224px)' });
const isSmallScreen = useMediaQuery({ query: '(max-width: 1224px)' });
return (
<div>
{isSmallScreen ? (
<LeftSidebar small={true} />
) : (
<LeftSidebar />
)}
</div>
);
}
In my implementation, I passed a small
prop to the LeftSidebar
component so that it could adjust its rendering accordingly.
Alternatively, you can create components that wrap JSX to create a cleaner structure:
import { useMediaQuery } from 'react-responsive';
const BigScreen = ({ children }) => {
return useMediaQuery({ minWidth: 992 }) ? children : null;
};
const SmallScreen = ({ children }) => {
return useMediaQuery({ maxWidth: 991 }) ? children : null;
};
export default function Layout({ children }) {
return (
<div>
<SmallScreen>
<LeftSidebar small={true} />
</SmallScreen>
<BigScreen>
<LeftSidebar />
</BigScreen>
</div>
);
}
Using these wrapper components provides a more readable structure in JSX.
Tags: React, JSX, responsive layouts, react-responsive