/

How to Make Responsive JSX in React

How to Make Responsive JSX in React

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.

Responsive Sidebar Example
Responsive Sidebar Example

To accomplish this, you can use the react-responsive package.

First, install the package using npm:

1
npm install react-responsive

Then, import the useMediaQuery hook into your components:

1
import { useMediaQuery } from 'react-responsive';

You can use the useMediaQuery hook like this:

1
2
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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