乐闻世界logo
搜索文章和话题

How to make ant-design Drawer component width responsive

1个答案

1

When using the Ant Design Drawer component, we aim to make its width dynamically adapt to the viewport size for a better responsive user experience. To achieve this, we can combine CSS media queries with React state management.

Step 1: Set the Basic Width of the Drawer Component

First, we need to set a basic width state in the React component, which will serve as the initial width for the Drawer component.

jsx
import React, { useState, useEffect } from 'react'; import { Drawer } from 'antd'; function ResponsiveDrawer() { const [drawerWidth, setDrawerWidth] = useState(300); // Set initial width to 300px return ( <Drawer title="Example Drawer" placement="right" width={drawerWidth} > <p>This is the drawer content...</p> </Drawer> ); } export default ResponsiveDrawer;

Step 2: Dynamically Adjust Width Using Media Queries

Next, we can use window.matchMedia or CSS @media queries to monitor changes in the viewport size and adjust the Drawer's width accordingly.

jsx
function ResponsiveDrawer() { const [drawerWidth, setDrawerWidth] = useState(300); useEffect(() => { function updateWidth() { if (window.innerWidth < 480) { setDrawerWidth(280); // For very small devices, set drawer width to 280px } else if (window.innerWidth < 768) { setDrawerWidth(320); // For small devices, set drawer width to 320px } else { setDrawerWidth(400); // For medium and larger devices, set drawer width to 400px } } window.addEventListener('resize', updateWidth); updateWidth(); // Initialize to set the correct width return () => { window.removeEventListener('resize', updateWidth); }; }, []); return ( <Drawer title="Example Drawer" placement="right" width={drawerWidth} > <p>This is the drawer content...</p> </Drawer> ); } export default ResponsiveDrawer;

Explanation

In the above example, we first use the useState Hook to set a drawerWidth state to store the current width of the Drawer. Then, we use the useEffect Hook to add an event listener for window resize events. Whenever the window size changes, we adjust the Drawer's width based on the current viewport width to adapt to different devices.

By doing this, regardless of whether the user is browsing on a mobile device, tablet, or desktop, the Drawer component provides an appropriate user experience.

2024年8月9日 20:46 回复

你的答案