In Ant Design, we can utilize the Row and Col components to build a responsive grid system. Ant Design's grid system is based on the 24-column grid principle, enabling us to implement different layouts across various screen sizes. Below are the steps and examples for creating a simple responsive grid using these components:
1. Import the Required Components
First, import the Row and Col components from the 'antd' library:
jsximport { Row, Col } from 'antd';
2. Create the Basic Row and Col Structure
Next, establish the fundamental row and column structure. For instance, to create a three-column layout:
jsx<Row> <Col span={8}>Column 1</Col> <Col span={8}>Column 2</Col> <Col span={8}>Column 3</Col> </Row>
Here, each Col component is configured with span={8}, meaning each column occupies 8/24 of the row width, equivalent to one-third of the row width.
3. Add Responsive Layout
To ensure the grid adapts to different device sizes, define layouts at various breakpoints using the xs, sm, md, lg, and xl properties within the Col component:
jsx<Row gutter={16}> <Col xs={24} sm={12} md={8} lg={6} xl={4}> Column 1 </Col> <Col xs={24} sm={12} md={8} lg={6} xl={4}> Column 2 </Col> <Col xs={24} sm={12} md={8} lg={6} xl={4}> Column 3 </Col> </Row>
In this example:
xs={24}indicates that on extra small screens (mobile), each column spans the full row.sm={12}indicates that on small screens (tablet), each column spans half the row width.md={8},lg={6}, andxl={4}represent the layouts for medium, large, and extra large screens respectively.
4. Adjust Spacing
Use the Row's gutter property to set spacing between columns. In the above code, gutter={16} specifies 16px spacing between each Col.
Example Application
Suppose we want to create a responsive grid layout for a product display page, where each product card dynamically adjusts its column width based on screen size:
jsximport { Row, Col, Card } from 'antd'; const products = [{ title: 'Product 1' }, { title: 'Product 2' }, { title: 'Product 3' }]; const ProductGrid = () => ( <Row gutter={16}> {products.map((product, index) => ( <Col key={index} xs={24} sm={12} md={8} lg={6} xl={4}> <Card title={product.title}> <p>Product details here...</p> </Card> </Col> ))} </Row> ); export default ProductGrid;
In this example, each product card dynamically adjusts its column width based on screen size, resulting in a clean and responsive layout.