」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 在 React 中建立響應式會議圖塊的動態網格系統

在 React 中建立響應式會議圖塊的動態網格系統

發佈於2024-11-06
瀏覽:441

Building a Dynamic Grid System for Responsive Meeting Tiles in React

In the era of remote work and virtual meetings, creating a responsive and dynamic grid system for displaying participant video tiles is crucial. Inspired by platforms like Google Meet, I recently developed a flexible grid system in React that adapts seamlessly to varying numbers of participants and different screen sizes. In this blog post, I'll walk you through the implementation, explaining the key components and how they work together to create an efficient and responsive layout.

Table of Contents

  1. Introduction
  2. Grid Layout Definitions
  3. Selecting the Appropriate Grid Layout
  4. The useGridLayout Hook
  5. Example Usage
  6. Styling the Grid
  7. Conclusion

Introduction

Creating a dynamic grid system involves adjusting the layout based on the number of items (or "tiles") and the available screen real estate. For video conferencing applications, this ensures that each participant's video feed is displayed optimally, regardless of the number of participants or the device being used.

The solution I developed leverages React hooks and CSS Grid to manage and render the grid layout dynamically. Let's dive into the core components of this system.

Grid Layout Definitions

First, we define the possible grid layouts that our system can use. Each layout specifies the number of columns and rows, as well as constraints on the minimum and maximum number of tiles it can accommodate.

import { useState, useEffect, RefObject } from 'react';

export type GridLayoutDefinition = {
  name: string;
  columns: number;
  rows: number;
  minTiles: number;
  maxTiles: number;
  minWidth: number;
  minHeight: number;
};

export const GRID_LAYOUTS: GridLayoutDefinition[] = [
  { columns: 1, rows: 1, name: '1x1', minTiles: 1, maxTiles: 1, minWidth: 0, minHeight: 0 },
  { columns: 1, rows: 2, name: '1x2', minTiles: 2, maxTiles: 2, minWidth: 0, minHeight: 0 },
  { columns: 2, rows: 1, name: '2x1', minTiles: 2, maxTiles: 2, minWidth: 900, minHeight: 0 },
  { columns: 2, rows: 2, name: '2x2', minTiles: 3, maxTiles: 4, minWidth: 560, minHeight: 0 },
  { columns: 3, rows: 3, name: '3x3', minTiles: 5, maxTiles: 9, minWidth: 700, minHeight: 0 },
  { columns: 4, rows: 4, name: '4x4', minTiles: 10, maxTiles: 16, minWidth: 960, minHeight: 0 },
  { columns: 5, rows: 5, name: '5x5', minTiles: 17, maxTiles: 25, minWidth: 1100, minHeight: 0 },
];

Explanation

  • GridLayoutDefinition: A TypeScript type that defines the properties of each grid layout.
  • GRID_LAYOUTS: An array of predefined layouts, ordered by complexity. Each layout specifies:
    • columns and rows: The number of columns and rows in the grid.
    • name: A descriptive name for the layout (e.g., '2x2').
    • minTiles and maxTiles: The range of tile counts that the layout can accommodate.
    • minWidth and minHeight: The minimum container dimensions required for the layout.

Selecting the Appropriate Grid Layout

The core logic for selecting the right grid layout based on the number of tiles and container size is encapsulated in the selectGridLayout function.

function selectGridLayout(
  layouts: GridLayoutDefinition[],
  tileCount: number,
  width: number,
  height: number,
): GridLayoutDefinition {
  let currentLayoutIndex = 0;
  let layout = layouts.find((layout_, index, allLayouts) => {
    currentLayoutIndex = index;
    const isBiggerLayoutAvailable = allLayouts.findIndex((l, i) => 
      i > index && l.maxTiles === layout_.maxTiles
    ) !== -1;
    return layout_.maxTiles >= tileCount && !isBiggerLayoutAvailable;
  });

  if (!layout) {
    layout = layouts[layouts.length - 1];
    console.warn(`No layout found for: tileCount: ${tileCount}, width/height: ${width}/${height}. Fallback to biggest available layout (${layout?.name}).`);
  }

  if (layout && (width  0) {
      const smallerLayout = layouts[currentLayoutIndex - 1];
      layout = selectGridLayout(
        layouts.slice(0, currentLayoutIndex),
        smallerLayout.maxTiles,
        width,
        height,
      );
    }
  }

  return layout || layouts[0];
}

How It Works

  1. Initial Selection: The function iterates through the layouts array to find the first layout where maxTiles is greater than or equal to tileCount and ensures there's no larger layout with the same maxTiles available.

  2. Fallback Mechanism: If no suitable layout is found, it defaults to the largest available layout and logs a warning.

  3. Responsive Adjustment: If the selected layout's minWidth or minHeight constraints aren't met by the container dimensions, the function recursively selects a smaller layout that fits within the constraints.

  4. Final Return: The selected layout is returned, ensuring that the grid is both adequate for the number of tiles and fits within the container's size.

The useGridLayout Hook

To encapsulate the grid selection logic and make it reusable across components, I created the useGridLayout custom hook.

export function useGridLayout(
  gridRef: RefObject,
  tileCount: number
): { layout: GridLayoutDefinition } {
  const [layout, setLayout] = useState(GRID_LAYOUTS[0]);

  useEffect(() => {
    const updateLayout = () => {
      if (gridRef.current) {
        const { width, height } = gridRef.current.getBoundingClientRect();
        const newLayout = selectGridLayout(GRID_LAYOUTS, tileCount, width, height);
        setLayout(newLayout);

        gridRef.current.style.setProperty('--col-count', newLayout.columns.toString());
        gridRef.current.style.setProperty('--row-count', newLayout.rows.toString());
      }
    };

    updateLayout();

    window.addEventListener('resize', updateLayout);
    return () => window.removeEventListener('resize', updateLayout);
  }, [gridRef, tileCount]);

  return { layout };
}

Hook Breakdown

  • Parameters:

    • gridRef: A reference to the grid container element.
    • tileCount: The current number of tiles to display.
  • State Management: Uses useState to keep track of the current layout, initializing with the first layout in GRID_LAYOUTS.

  • Effect Hook:

    • updateLayout Function: Retrieves the container's width and height, selects the appropriate layout using selectGridLayout, and updates the state. It also sets CSS variables --col-count and --row-count on the container for styling.
    • Event Listener: Adds a resize event listener to update the layout whenever the window size changes. Cleans up the listener on component unmount.
  • Return Value: Provides the current layout object to the consuming component.

Example Usage

To demonstrate how this dynamic grid system works in practice, here's an example React component that uses the useGridLayout hook.

'use client'

import React, { useState, useRef, useEffect } from 'react'
import { Button } from "@/components/ui/button"
import { useGridLayout, GridLayoutDefinition } from './useGridLayout'

export default function Component() {
  const [tiles, setTiles] = useState([1, 2, 3, 4]);
  const [containerWidth, setContainerWidth] = useState(typeof window !== 'undefined' ? window.innerWidth : 1000);
  const gridRef = useRef(null);

  const { layout } = useGridLayout(gridRef, tiles.length);

  useEffect(() => {
    const handleResize = () => {
      setContainerWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const addTile = () => setTiles(prev => [...prev, prev.length   1]);
  const removeTile = () => setTiles(prev => prev.slice(0, -1));

  return (
    
{tiles.slice(0, layout.maxTiles).map((tile) => (
Tile {tile}
))}

Current Layout: {layout.name} ({layout.columns}x{layout.rows})

Container Width: {containerWidth}px

Visible Tiles: {Math.min(tiles.length, layout.maxTiles)} / Total Tiles: {tiles.length}

) }

Component Breakdown

  1. State Management:

    • tiles: An array representing the current tiles. Initially contains four tiles.
    • containerWidth: Tracks the container's width, updating on window resize.
  2. Refs:

    • gridRef: A reference to the grid container, passed to the useGridLayout hook.
  3. Using the Hook:

    • Destructures the layout object from the useGridLayout hook, which determines the current grid layout based on the number of tiles and container size.
  4. Event Handling:

    • Add Tile: Adds a new tile to the grid.
    • Remove Tile: Removes the last tile from the grid.
    • Resize Listener: Updates containerWidth on window resize.
  5. Rendering:

    • Controls: Buttons to add or remove tiles.
    • Grid Container:
      • Uses CSS Grid with dynamic gridTemplateColumns and gridTemplateRows based on CSS variables set by the hook.
      • Renders tiles up to the layout.maxTiles limit.
    • Info Section: Displays the current layout, container width, and the number of visible versus total tiles.

What Happens in Action

  • Adding Tiles: As you add more tiles, the useGridLayout hook recalculates the appropriate grid layout to accommodate the new number of tiles while respecting the container's size.
  • Removing Tiles: Removing tiles triggers a layout recalculation to potentially use a smaller grid layout, optimizing space.
  • Resizing: Changing the window size dynamically adjusts the grid layout to ensure that the tiles remain appropriately sized and positioned.

Styling the Grid

The grid's responsiveness is primarily handled via CSS Grid properties and dynamically set CSS variables. Here's a brief overview of how the styling works:

/* Example Tailwind CSS classes used in the component */
/* The actual styles are managed via Tailwind, but the key dynamic properties are set inline */

.grid {
  display: grid;
  gap: 1rem; /* Adjust as needed */
}

.grid > div {
  /* Example styles for tiles */
  background-color: var(--color-primary, #3490dc);
  color: var(--color-primary-foreground, #ffffff);
  padding: 1rem;
  border-radius: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

Dynamic CSS Variables

In the useGridLayout hook, the following CSS variables are set based on the selected layout:

  • --col-count: Number of columns in the grid.
  • --row-count: Number of rows in the grid.

These variables are used to define the gridTemplateColumns and gridTemplateRows properties inline:

style={{
  gridTemplateColumns: `repeat(var(--col-count), 1fr)`,
  gridTemplateRows: `repeat(var(--row-count), 1fr)`,
}}

This approach ensures that the grid layout adapts seamlessly without the need for extensive CSS media queries.

Conclusion

Building a dynamic grid system for applications like video conferencing requires careful consideration of both the number of elements and the available display space. By defining a set of responsive grid layouts and implementing a custom React hook to manage layout selection, we can create a flexible and efficient system that adapts in real-time to user interactions and screen size changes.

This approach not only enhances the user experience by providing an optimal viewing arrangement but also simplifies the development process by encapsulating the layout logic within reusable components. Whether you're building a video conferencing tool, a dashboard, or any application that requires dynamic content arrangement, this grid system can be a valuable addition to your toolkit.

Feel free to customize and extend this system to suit your specific needs. Happy coding!

版本聲明 本文轉載於:https://dev.to/vaib215/building-a-dynamic-grid-system-for-responsive-meeting-tiles-in-react-443l?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 讓您的網頁更快
    讓您的網頁更快
    什么是 DOM?它吃什么? DOM(文档对象模型)是网页及其开发的基础。它是 HTML 和 XML 文档的编程接口,以树状对象表示文档的结构。有树枝和树叶。文档中的每个元素、属性和文本片段都成为该树中的一个节点。它允许 JavaScript 与 HTML 元素交互、修改它们或添加新...
    程式設計 發佈於2024-11-07
  • JavaScript 中的 require 與 import
    JavaScript 中的 require 與 import
    我記得當我開始編碼時,我會看到一些js檔案使用require()來匯入模組和其他檔案使用import。這總是讓我感到困惑,因為我並不真正理解其中的差異是什麼,或者為什麼專案之間存在不一致。如果您想知道同樣的事情,請繼續閱讀! 什麼是 CommonJS? CommonJS 是一組用於...
    程式設計 發佈於2024-11-07
  • 使用鏡像部署 Vite/React 應用程式:完整指南
    使用鏡像部署 Vite/React 應用程式:完整指南
    在 GitHub Pages 上部署 Vite/React 应用程序是一个令人兴奋的里程碑,但这个过程有时会带来意想不到的挑战,特别是在处理图像和资产时。这篇博文将引导您完成整个过程,从最初的部署到解决常见问题并找到有效的解决方案。 无论您是初学者还是有经验的人,本指南都将帮助您避免常见的陷阱,并...
    程式設計 發佈於2024-11-07
  • 我如何在我的 React 應用程式中優化 API 呼叫
    我如何在我的 React 應用程式中優化 API 呼叫
    作为 React 开发者,我们经常面临需要通过 API 同步多个快速状态变化的场景。对每一个微小的变化进行 API 调用可能效率低下,并且会给客户端和服务器带来负担。这就是去抖和巧妙的状态管理发挥作用的地方。在本文中,我们将构建一个自定义 React 钩子,通过合并有效负载和去抖 API 调用来捕获...
    程式設計 發佈於2024-11-07
  • 我們走吧!
    我們走吧!
    為什麼你需要嘗試 GO Go 是一種快速、輕量級、靜態類型的編譯語言,非常適合建立高效、可靠的應用程式。它的簡單性和簡潔的語法使其易於學習和使用,特別是對於新手來說。 Go 的突出功能包括內建的 goroutine 並發性、強大的標準庫以及用於程式碼格式化、測試和依賴管理的強大工具...
    程式設計 發佈於2024-11-06
  • 如何將 PNG 圖像編碼為 CSS 資料 URI 的 Base64?
    如何將 PNG 圖像編碼為 CSS 資料 URI 的 Base64?
    在CSS 資料URI 中對PNG 圖像使用Base64 編碼為了使用資料URI 將PNG 圖片嵌入到CSS 樣式表中,PNG資料必須先編碼為Base64 格式。此技術允許將外部圖像檔案直接包含在樣式表中。 Unix 命令列解決方案:base64 -i /path/to/image.png此指令將輸出...
    程式設計 發佈於2024-11-06
  • API 每小時資料的響應式 JavaScript 輪播
    API 每小時資料的響應式 JavaScript 輪播
    I almost mistook an incomplete solution for a finished one and moved on to work on other parts of my weather app! While working on the carousel that w...
    程式設計 發佈於2024-11-06
  • 用於 Web 開發的 PHP 和 JavaScript 之間的主要差異是什麼?
    用於 Web 開發的 PHP 和 JavaScript 之間的主要差異是什麼?
    PHP 與 JavaScript:伺服器端與客戶端 PHP 的作用與 JavaScript 不同。 PHP 運行在伺服器端。伺服器運行應用程式。除此之外,它還處理表單。當您提交表單時,PHP 會對其進行處理。另一方面,JavaScript 是客戶端的。它在瀏覽器中運行。它處理頁面互...
    程式設計 發佈於2024-11-06
  • 如何在 C++ 中迭代結構和類別成員以在運行時存取它們的名稱和值?
    如何在 C++ 中迭代結構和類別成員以在運行時存取它們的名稱和值?
    迭代結構體和類別成員在 C 中,可以迭代結構體或類別的成員來檢索它們的名稱和價值觀。以下是實現此目的的幾種方法:使用巨集REFLECTABLE 巨集可用於定義允許自省的結構。該巨集將結構體的成員定義為以逗號分隔的類型名稱對清單。例如:struct A { REFLECTABLE ( ...
    程式設計 發佈於2024-11-06
  • 如果需要準確答案,請避免浮動和雙精度
    如果需要準確答案,請避免浮動和雙精度
    float 和 double 問題: 專為科學和數學計算而設計,執行二元浮點運算。 不適合貨幣計算或需要精確答案的情況。 無法準確表示10的負次方,例如0.1,從而導致錯誤。 範例1: 減去美元金額時計算錯誤: System.out.println(1.03 - 0.42); // Resu...
    程式設計 發佈於2024-11-06
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-06
  • 如何在 Python 中使用代理程式運行 Selenium Webdriver?
    如何在 Python 中使用代理程式運行 Selenium Webdriver?
    使用Python 中的代理程式執行Selenium Webdriver當您嘗試將Selenium Webdriver 腳本匯出為Python 腳本並從命令列執行時,可能會遇到在使用代理的情況下出現錯誤。本文旨在解決此問題,提供使用代理有效運行腳本的解決方案。 代理整合要使用代理程式來執行 Selen...
    程式設計 發佈於2024-11-06
  • || 什麼時候運算子充當 JavaScript 中的預設運算子?
    || 什麼時候運算子充當 JavaScript 中的預設運算子?
    理解|| 的目的JavaScript 中非布林運算元的運算子在JavaScript 中,||運算子通常稱為邏輯OR 運算符,通常用於計算布林表達式。但是,您可能會遇到 || 的情況。運算符與非布林值一起使用。 在這種情況下,||運算子的行為類似於「預設」運算子。它不傳回布林值,而是根據某些規則傳回左...
    程式設計 發佈於2024-11-06
  • 探索 Java 23 的新特性
    探索 Java 23 的新特性
    親愛的開發者、程式設計愛好者和學習者, Java 開發工具包 (JDK) 23 已正式發布(2024/09/17 正式發布),標誌著 Java 程式語言發展的另一個重要里程碑。此最新更新引入了大量令人興奮的功能和增強功能,旨在改善開發人員體驗、效能和模組化。 在本文中,我將分享 JDK 23 的一...
    程式設計 發佈於2024-11-06
  • ES6 陣列解構:為什麼它沒有如預期般運作?
    ES6 陣列解構:為什麼它沒有如預期般運作?
    ES6 陣列解構:不可預見的行為在ES6 中,陣列的解構賦值可能會導致意外的結果,讓程式設計師感到困惑。下面的程式碼說明了一個這樣的實例:let a, b, c [a, b] = ['A', 'B'] [b, c] = ['BB', 'C'] console.log(`a=${a} b=${b} c...
    程式設計 發佈於2024-11-06

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3