preface

Recently, I came into contact with a React-grid-layout system. I found that it has a lot of functions, but I do not understand the use of attributes and events in it. Therefore, I summarized (translated) its attributes and uses

react-grid-layout

React-grid-layout is a Grid Layout system for React components that does not require JQuery. Packery and Gridster, but RGL is responsive and supports breakpoints, which can be set by the user or automatically generated by RGL. Powerful GIFs from the official website:

Grid Layout Props

RGL supports the following attributes:

Basic properties

// Base attributes
The width property is required unless you use HOC 
      
        or some other similar component.
      
width: number,

// When true, the container is highly adaptive to the contentautoSize: ? boolean =true.// Divide the current layout into columnscols: ? number =12| {},// A CSS selector whose property value is tag. Tag cannot be dragged after being tagged
/ /, for example: draggableCancel: 'MyNonDraggableAreaClassName'draggableCancel: ? string =' '.// A CSS selector whose property value is tag. Tag can be dragged after being tagged
// For example: draggableHandle:'.MyDragHandleClassName'draggableHandle: ? string =' '.// When true, it compacts verticallyverticalCompact: ? boolean =true.// The direction of the compact arrangementcompactType: ? ('vertical' | 'horizontal') = 'vertical';

// Layouts are an array of {x: number, y: number, w: number, h: number} objects
// Note that layout subscripts in the array must match the key value of the component on which they are applied
// If you want to use a custom key in a component, you can specify that key in layout
// The last array of objects might look like this: {I: string, x: number, y: number, w: number, h: number}
// Can also be set separately in child componentslayout: ? array =null.// Margin between each contained block: [x,y] in pxmargin: ? [number, number] = [10.10].// Contains the padding inside the block :[x,y] in px
// Padding inside the container [x, y] in pxcontainerPadding: ? [number, number] = margin,// Static height of each row, but you can change it based on breakpoints if necessary,rowHeight: ? number =150.// Configuration of the Droping element, which is a "virtual" element that appears when you drag an element externally
// It can be changed by passing certain arguments:
// I - the element id
// w - Width of the element
// The height of the h - elementdroppingItem? : {i: string, w: number, h: number }

//
// Flags
//isDraggable: ? boolean =true.isResizable: ?boolean = true.// Using CSS3 translate() instead of top and left in positioning improves drawing performance by up to 6 timesuseCSSTransforms: ? boolean =true./ / if the parent node: ResponsiveReactGridLayout or ReactGridLayout transform: scale (n) of CSS properties
// We should set the scaling coefficient to avoid rendering artefacts during draggingtransformScale: ? number =1.// If set to true, the dragged component does not change position during the drag processpreventCollision: ? boolean =false;

// If set to true, dragable elements (with draggable={true}) can be dragged on the grid, which raises the "onDrop" callback, to which location information and event objects are passed as arguments.

/ / note: If you are using Firefox you should add onDragStart={e => e.datatransfer.setData ('text/plain', '')} attributes and draggable={true} otherwise this feature will not work correctly
// Firefox requires the onDragStart attribute for drag-and-drop initialization
// @see https://bugzilla.mozilla.org/show_bug.cgi?id=568313isDroppable: ? boolean =false

//
// Callbacks
//

// This callback is used to save the layout, and returns the current layout after each drag or resize
onLayoutChange: (layout: Layout) = > void.// All of the following callbacks have these parameters (Layout, oldItem, newItem, placeholder, E, Element)
// Placeholder is undefined in the start and end callback
//
type ItemCallback = (layout: Layout, oldItem: LayoutItem, newItem: LayoutItem,
                     placeholder: LayoutItem, e: MouseEvent, element: HTMLElement) => void;


onDragStart: ItemCallback,
onDrag: ItemCallback,
onDragStop: ItemCallback,
onResizeStart: ItemCallback,
onResize: ItemCallback,
onResizeStop: ItemCallback,
onDrop: (elemParams: { x: number, y: number, e: Event }) = > void
Copy the code

Responsive raster layout properties

Responsive raster layouts are available and support all basic properties except 👆 layout. The new properties and changes are as follows:

// The breakpoint name is arbitrary, but must match the COLs and layouts objects.
breakpoints: ?Object = {lg: 1200.md: 996.sm: 768.xs: 480.xxs: 0},

// Breakpoint for COLs
cols: ?Object = {lg: 12.md: 10.sm: 6.xs: 4.xxs: 2},

/ / fixed interval or reactive intervals e.g. [10, 10] | ` {lg: [10, 10], md: [10, 10],... }.
margin: [number, number] | {[breakpoint: $Keys<breakpoints>]: [number, number]}


/ / same as above, fixed padding or reactive padding: e.g. [10, 10] | ` {lg: [10, 10], md: [10, 10],... }
containerPadding: [number, number] | {[breakpoint: $Keys<breakpoints>]: [number, number]}


{lg: Layout, MD: Layout,... }
layouts: {[key: $Keys<breakpoints>]: Layout}

//
// Callbacks
//

onBreakpointChange: (newBreakpoint: string, newCols: number) = > void.onLayoutChange: (currentLayout: Layout, allLayouts: {[key: $Keys<breakpoints>]: Layout}) = > void.// Callback when the page width changes, so that you can modify the layout as needed
onWidthChange: (containerWidth: number, margin: [number, number], cols: number, containerPadding: [number, number]) = > void;
Copy the code

Properties of grid elements

Note that if a grid item is provided but incomplete (missing one of x, Y, W, or H) an error will be thrown so that you can correct the layout.

If no attributes are provided for the grid item, an attribute of width and height 1 is generated.

You can set a minimum and maximum value for each dimension. This is for resizing; Of course, if the resizing function is disabled, there is no impact. An error will be thrown if your minimum and maximum values overlap, or if your initial size is out of range.

Any attributes defined directly in <GridItem> will take precedence over those in the global. For example, if the layout property is isDraggable: false, but the grid item is isDraggable: true in the props object, then the grid item isDraggable, even if it is marked static: true.

{

  // The key of the component
  i: string,

  // These are grid cells, not pixels
  x: number, / / a few columns
  y: number, // multiple of rowHeight
  w: number, // Same as x
  h: number, // Same as yminW: ? number =0.maxW: ?number = Infinity.minH: ?number = 0.maxH: ?number = Infinity.// isDraggable: false, isResizable: false
  static: ?boolean = false.// Cannot be dragged to override the static attribute when falseisDraggable: ? boolean =true.// Set the size to false to override the static attributeisResizable: ? boolean =true
}
Copy the code

use

Component selection

Non-responsive direct reference to the GridLayout component as follows:

import GridLayout from 'react-grid-layout';
Copy the code

GridLayout does not support cols, layouts, or other breakpoint adjustment properties that are based on breakpoint adjustment objects (eg:{LG: 1200, MD: 996, SM: 768, XS: 480, XXS: 0}), forcing the page to look different from what it is supposed to look like is a mistake. Use the following components when you want to use responsive layouts.

Responsive use method:

When using reactive mode, you should have the layouts attribute value provide at least one breakpoint layout, and breakpoint layout for individual Grid-items is not currently supported.

Use the ResponsiveGridLayout component

import { Responsive as ResponsiveGridLayout } from 'react-grid-layout';
Copy the code

2. Use the WidthProvider function to wrap the component

import { Responsive, WidthProvider } from 'react-grid-layout';

const ResponsiveGridLayout = WidthProvider(Responsive);
Copy the code

Difference: The

and

components use width to calculate position in drag events, so width is required when using both components. Now there are simpler components: WidthProvider, for which the width property is not required, and which are automatically calculated during initialization and resize events after wrapping a component with WidthProvider

Use of breakpoints

Many of the attributes that can be used as objects support layout control based on breakpoints, such as cols, layouts, containerPadding, and Margin. For example, margin:

import React from "react";
import {WidthProvider, Responsive} from 'react-grid-layout';

const ResponsiveGridLayout = WidthProvider(Responsive);
export default class MyFirstGrid extends React.Component {
  render() {
    const layout = [
      {i: 'a'.x: 0.y: 0.w: 1.h: 2.static: true},
      {i: 'b'.x: 1.y: 0.w: 2.h: 2.minW: 2.maxW: 4},
      {i: 'c'.x: 0.y: 2.w: 1.h: 2}];return (
      <ResponsiveGridLayout className="layout" 
        layouts={{lg:layout} } 
        rowHeight={30}
        breakpoints={{lg: 1200.md: 996.sm: 768.xs: 480.xxs: 0}}
        margin={{lg: [30.30].md: [20.20].sm: [10.10].xs: [5.5]}}
      >
        <div key="a" style={{"background": "red}} ">a</div>
        <div key="b" style={{"background": "red}} ">b</div>
        <div key="c" style={{"background": "red}} ">c</div>
      </ResponsiveGridLayout>)}}Copy the code

The effect is as follows:

You can see that the element spacing changes at the breakpoint.

More complex, if you want to control the placement of elements in the X and Y coordinates of each element, you can use the layouts attribute to change the placement of elements for different screen sizes.

Some event functions that assist in reactive change

  • OnBreakpointChange is triggered when the page size transitions from one breakpoint interval to another. It can be used to modify reactive properties (eg: rowHeight) that are not supported natively
  • OnLayoutChange similar to onBreakpointChange is triggered at the location of the breakpoint. Callbacks pass in values of the layout and layouts properties to change the layout of the key
  • OnWidthChange Callback to the page size change, passing in the container width, the current margin value, cols value, and containerPadding value

Use a compact alignment

The entire page is marked with (0,0) in the upper left corner.

Among the basic properties, notice that there are two properties: verticalCompact and compactType, Boolean and String respectively, that indicate whether or in what direction the vertical alignment is compact. If both compactType and verticalCompact exist, compactType has a higher priority than verticalCompact.

Using different alignment will make arrangement of the page have different magical effect: use vertically aligned to the same position as the abscissa if this element has occupied the position of the front element in the front of the same (i.e., the vertical), then the elements in the lower part of the last element, under the same abscissa otherwise in the position of (x, 0);

Use of horizontal alignment, transverse and longitudinal coordinate phase at the same time, from left to right rear newcomers left, except those marked as static, will keep on their x coordinates, ordinate the same abscissa is different, according to the numerical size of abscissa arranged from left to right, the same horizontal ordinate is different, in front of the ordinate elements have occupied the position, So it’s to the right of the last element.

conclusion

In some business scenarios, it is necessary to use such a grid system to fragment and fill the page, so it is convenient to use RGL, but it may not be in-depth in practice. There are also some problems in practice according to the example on Github. For example, the Grid-item cannot be resized even after isResizable is set. The response feature, drag feature and grid-item resize feature will be summarized and supplemented in the future practice.