项目作者: react-grid-layout

项目描述 :
A draggable and resizable grid layout with responsive breakpoints, for React.
高级语言: JavaScript
项目地址: git://github.com/react-grid-layout/react-grid-layout.git
创建时间: 2014-12-27T14:28:40Z
项目社区:https://github.com/react-grid-layout/react-grid-layout

开源协议:MIT License

下载


React-Grid-Layout

travis build
CDNJS
npm package
npm downloads

React-Grid-Layout is a grid layout system much like Packery or
Gridster, for React.

Unlike those systems, it is responsive and supports breakpoints. Breakpoint layouts can be provided by the user
or autogenerated.

RGL is React-only and does not require jQuery.

BitMEX UI

GIF from production usage on BitMEX.com

[Demo | Changelog | CodeSandbox Editable demo]

Table of Contents

Demos

  1. Showcase
  2. Basic
  3. No Dragging/Resizing (Layout Only)
  4. Messy Layout Autocorrect
  5. Layout Defined on Children
  6. Static Elements
  7. Adding/Removing Elements
  8. Saving Layout to LocalStorage
  9. Saving a Responsive Layout to LocalStorage
  10. Minimum and Maximum Width/Height
  11. Dynamic Minimum and Maximum Width/Height
  12. No Vertical Compacting (Free Movement)
  13. Prevent Collision
  14. Error Case
  15. Toolbox
  16. Drag From Outside
  17. Bounded Layout
  18. Responsive Bootstrap-style Layout
  19. Scaled Containers
  20. Allow Overlap
  21. All Resizable Handles
  22. Single Row Horizontal

Projects Using React-Grid-Layout

Know of others? Create a PR to let me know!

Features

  • 100% React - no jQuery
  • Compatible with server-rendered apps
  • Draggable widgets
  • Resizable widgets
  • Static widgets
  • Configurable packing: horizontal, vertical, or off
  • Bounds checking for dragging and resizing
  • Widgets may be added or removed without rebuilding grid
  • Layout can be serialized and restored
  • Responsive breakpoints
  • Separate layouts per responsive breakpoint
  • Grid Items placed using CSS Transforms
    • Performance with CSS Transforms: on / off, note paint (green) as % of time
  • Compatibility with <React.StrictMode>
Version Compatibility
>= 0.17.0 React 16 & 17
>= 0.11.3 React 0.14 & 15
>= 0.10.0 React 0.14
0.8. - 0.9.2 React 0.13
< 0.8 React 0.12

Installation

Install the React-Grid-Layout package using npm:

  1. npm install react-grid-layout

Include the following stylesheets in your application:

  1. /node_modules/react-grid-layout/css/styles.css
  2. /node_modules/react-resizable/css/styles.css

Usage

Use ReactGridLayout like any other component. The following example below will
produce a grid with three items where:

  • users will not be able to drag or resize item a
  • item b will be restricted to a minimum width of 2 grid blocks and a maximum width of 4 grid blocks
  • users will be able to freely drag and resize item c
  1. import GridLayout from "react-grid-layout";
  2. class MyFirstGrid extends React.Component {
  3. render() {
  4. // layout is an array of objects, see the demo for more complete usage
  5. const layout = [
  6. { i: "a", x: 0, y: 0, w: 1, h: 2, static: true },
  7. { i: "b", x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 },
  8. { i: "c", x: 4, y: 0, w: 1, h: 2 }
  9. ];
  10. return (
  11. <GridLayout
  12. className="layout"
  13. layout={layout}
  14. cols={12}
  15. rowHeight={30}
  16. width={1200}
  17. >
  18. <div key="a">a</div>
  19. <div key="b">b</div>
  20. <div key="c">c</div>
  21. </GridLayout>
  22. );
  23. }
  24. }

You may also choose to set layout properties directly on the children:

  1. import GridLayout from "react-grid-layout";
  2. class MyFirstGrid extends React.Component {
  3. render() {
  4. return (
  5. <GridLayout className="layout" cols={12} rowHeight={30} width={1200}>
  6. <div key="a" data-grid={{ x: 0, y: 0, w: 1, h: 2, static: true }}>
  7. a
  8. </div>
  9. <div key="b" data-grid={{ x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4 }}>
  10. b
  11. </div>
  12. <div key="c" data-grid={{ x: 4, y: 0, w: 1, h: 2 }}>
  13. c
  14. </div>
  15. </GridLayout>
  16. );
  17. }
  18. }

Usage without Browserify/Webpack

A module usable in a <script> tag is included here. It uses a UMD shim and
excludes React, so it must be otherwise available in your application, either via RequireJS or on window.React.

Responsive Usage

To make RGL responsive, use the <ResponsiveReactGridLayout> element:

  1. import { Responsive as ResponsiveGridLayout } from "react-grid-layout";
  2. class MyResponsiveGrid extends React.Component {
  3. render() {
  4. // {lg: layout1, md: layout2, ...}
  5. const layouts = getLayoutsFromSomewhere();
  6. return (
  7. <ResponsiveGridLayout
  8. className="layout"
  9. layouts={layouts}
  10. breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
  11. cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
  12. >
  13. <div key="1">1</div>
  14. <div key="2">2</div>
  15. <div key="3">3</div>
  16. </ResponsiveGridLayout>
  17. );
  18. }
  19. }

When in responsive mode, you should supply at least one breakpoint via the layouts property.

When using layouts, it is best to supply as many breakpoints as possible, especially the largest one.
If the largest is provided, RGL will attempt to interpolate the rest.

You will also need to provide a width, when using <ResponsiveReactGridLayout> it is suggested you use the HOC
WidthProvider as per the instructions below.

It is possible to supply default mappings via the data-grid property on individual
items, so that they would be taken into account within layout interpolation.

Providing Grid Width

Both <ResponsiveReactGridLayout> and <ReactGridLayout> take width to calculate
positions on drag events. In simple cases a HOC WidthProvider can be used to automatically determine
width upon initialization and window resize events.

  1. import { Responsive, WidthProvider } from "react-grid-layout";
  2. const ResponsiveGridLayout = WidthProvider(Responsive);
  3. class MyResponsiveGrid extends React.Component {
  4. render() {
  5. // {lg: layout1, md: layout2, ...}
  6. var layouts = getLayoutsFromSomewhere();
  7. return (
  8. <ResponsiveGridLayout
  9. className="layout"
  10. layouts={layouts}
  11. breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
  12. cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
  13. >
  14. <div key="1">1</div>
  15. <div key="2">2</div>
  16. <div key="3">3</div>
  17. </ResponsiveGridLayout>
  18. );
  19. }
  20. }

This allows you to easily replace WidthProvider with your own Provider HOC if you need more sophisticated logic.

WidthProvider accepts a single prop, measureBeforeMount. If true, WidthProvider will measure the
container’s width before mounting children. Use this if you’d like to completely eliminate any resizing animation
on application/component mount.

Have a more complicated layout? WidthProvider is very simple and only
listens to window 'resize' events. If you need more power and flexibility, try the
SizeMe React HOC as an alternative to WidthProvider.

Grid Layout Props

RGL supports the following properties (see the source for the final word on this):

  1. //
  2. // Basic props
  3. //
  4. // This allows setting the initial width on the server side.
  5. // This is required unless using the HOC <WidthProvider> or similar
  6. width: number,
  7. // If true, the container height swells and contracts to fit contents
  8. autoSize: ?boolean = true,
  9. // Number of columns in this layout.
  10. cols: ?number = 12,
  11. // A CSS selector for tags that will not be draggable.
  12. // For example: draggableCancel:'.MyNonDraggableAreaClassName'
  13. // If you forget the leading . it will not work.
  14. // .react-resizable-handle" is always prepended to this value.
  15. draggableCancel: ?string = '',
  16. // A CSS selector for tags that will act as the draggable handle.
  17. // For example: draggableHandle:'.MyDragHandleClassName'
  18. // If you forget the leading . it will not work.
  19. draggableHandle: ?string = '',
  20. // Compaction type.
  21. compactType: ?('vertical' | 'horizontal' | null) = 'vertical';
  22. // Layout is an array of objects with the format:
  23. // The index into the layout must match the key used on each item component.
  24. // If you choose to use custom keys, you can specify that key in the layout
  25. // array objects using the `i` prop.
  26. layout: ?Array<{i?: string, x: number, y: number, w: number, h: number}> = null, // If not provided, use data-grid props on children
  27. // Margin between items [x, y] in px.
  28. margin: ?[number, number] = [10, 10],
  29. // Padding inside the container [x, y] in px
  30. containerPadding: ?[number, number] = margin,
  31. // Rows have a static height, but you can change this based on breakpoints
  32. // if you like.
  33. rowHeight: ?number = 150,
  34. // Configuration of a dropping element. Dropping element is a "virtual" element
  35. // which appears when you drag over some element from outside.
  36. // It can be changed by passing specific parameters:
  37. // i - id of an element
  38. // w - width of an element
  39. // h - height of an element
  40. droppingItem?: { i: string, w: number, h: number }
  41. //
  42. // Flags
  43. //
  44. isDraggable: ?boolean = true,
  45. isResizable: ?boolean = true,
  46. isBounded: ?boolean = false,
  47. // Uses CSS3 translate() instead of position top/left.
  48. // This makes about 6x faster paint performance
  49. useCSSTransforms: ?boolean = true,
  50. // If parent DOM node of ResponsiveReactGridLayout or ReactGridLayout has "transform: scale(n)" css property,
  51. // we should set scale coefficient to avoid render artefacts while dragging.
  52. transformScale: ?number = 1,
  53. // If true, grid can be placed one over the other.
  54. // If set, implies `preventCollision`.
  55. allowOverlap: ?boolean = false,
  56. // If true, grid items won't change position when being
  57. // dragged over. If `allowOverlap` is still false,
  58. // this simply won't allow one to drop on an existing object.
  59. preventCollision: ?boolean = false,
  60. // If true, droppable elements (with `draggable={true}` attribute)
  61. // can be dropped on the grid. It triggers "onDrop" callback
  62. // with position and event object as parameters.
  63. // It can be useful for dropping an element in a specific position
  64. //
  65. // NOTE: In case of using Firefox you should add
  66. // `onDragStart={e => e.dataTransfer.setData('text/plain', '')}` attribute
  67. // along with `draggable={true}` otherwise this feature will work incorrect.
  68. // onDragStart attribute is required for Firefox for a dragging initialization
  69. // @see https://bugzilla.mozilla.org/show_bug.cgi?id=568313
  70. isDroppable: ?boolean = false,
  71. // Defines which resize handles should be rendered.
  72. // Allows for any combination of:
  73. // 's' - South handle (bottom-center)
  74. // 'w' - West handle (left-center)
  75. // 'e' - East handle (right-center)
  76. // 'n' - North handle (top-center)
  77. // 'sw' - Southwest handle (bottom-left)
  78. // 'nw' - Northwest handle (top-left)
  79. // 'se' - Southeast handle (bottom-right)
  80. // 'ne' - Northeast handle (top-right)
  81. //
  82. // Note that changing this property dynamically does not work due to a restriction in react-resizable.
  83. resizeHandles: ?Array<'s' | 'w' | 'e' | 'n' | 'sw' | 'nw' | 'se' | 'ne'> = ['se'],
  84. // Custom component for resize handles
  85. // See `handle` as used in https://github.com/react-grid-layout/react-resizable#resize-handle
  86. // Your component should have the class `.react-resizable-handle`, or you should add your custom
  87. // class to the `draggableCancel` prop.
  88. resizeHandle?: ReactElement<any> | ((resizeHandleAxis: ResizeHandleAxis, ref: ReactRef<HTMLElement>) => ReactElement<any>),
  89. //
  90. // Callbacks
  91. //
  92. // Callback so you can save the layout.
  93. // Calls back with (currentLayout) after every drag or resize stop.
  94. onLayoutChange: (layout: Layout) => void,
  95. //
  96. // All callbacks below have signature (layout, oldItem, newItem, placeholder, e, element).
  97. // 'start' and 'stop' callbacks pass `undefined` for 'placeholder'.
  98. //
  99. type ItemCallback = (layout: Layout, oldItem: LayoutItem, newItem: LayoutItem,
  100. placeholder: LayoutItem, e: MouseEvent, element: HTMLElement) => void,
  101. // Calls when drag starts.
  102. onDragStart: ItemCallback,
  103. // Calls on each drag movement.
  104. onDrag: ItemCallback,
  105. // Calls when drag is complete.
  106. onDragStop: ItemCallback,
  107. // Calls when resize starts.
  108. onResizeStart: ItemCallback,
  109. // Calls when resize movement happens.
  110. onResize: ItemCallback,
  111. // Calls when resize is complete.
  112. onResizeStop: ItemCallback,
  113. //
  114. // Dropover functionality
  115. //
  116. // Calls when an element has been dropped into the grid from outside.
  117. onDrop: (layout: Layout, item: ?LayoutItem, e: Event) => void,
  118. // Calls when an element is being dragged over the grid from outside as above.
  119. // This callback should return an object to dynamically change the droppingItem size
  120. // Return false to short-circuit the dragover
  121. onDropDragOver: (e: DragOverEvent) => ?({|w?: number, h?: number|} | false),
  122. // Ref for getting a reference for the grid's wrapping div.
  123. // You can use this instead of a regular ref and the deprecated `ReactDOM.findDOMNode()`` function.
  124. // Note that this type is React.Ref<HTMLDivElement> in TypeScript, Flow has a bug here
  125. // https://github.com/facebook/flow/issues/8671#issuecomment-862634865
  126. innerRef: {current: null | HTMLDivElement},

Responsive Grid Layout Props

The responsive grid layout can be used instead. It supports all of the props above, excepting layout.
The new properties and changes are:

  1. // {name: pxVal}, e.g. {lg: 1200, md: 996, sm: 768, xs: 480}
  2. // Breakpoint names are arbitrary but must match in the cols and layouts objects.
  3. breakpoints: ?Object = {lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0},
  4. // # of cols. This is a breakpoint -> cols map, e.g. {lg: 12, md: 10, ...}
  5. cols: ?Object = {lg: 12, md: 10, sm: 6, xs: 4, xxs: 2},
  6. // margin (in pixels). Can be specified either as horizontal and vertical margin, e.g. `[10, 10]` or as a breakpoint -> margin map, e.g. `{lg: [10, 10], md: [10, 10], ...}.
  7. margin: [number, number] | {[breakpoint: $Keys<breakpoints>]: [number, number]},
  8. // containerPadding (in pixels). Can be specified either as horizontal and vertical padding, e.g. `[10, 10]` or as a breakpoint -> containerPadding map, e.g. `{lg: [10, 10], md: [10, 10], ...}.
  9. containerPadding: [number, number] | {[breakpoint: $Keys<breakpoints>]: [number, number]},
  10. // layouts is an object mapping breakpoints to layouts.
  11. // e.g. {lg: Layout, md: Layout, ...}
  12. layouts: {[key: $Keys<breakpoints>]: Layout},
  13. //
  14. // Callbacks
  15. //
  16. // Calls back with breakpoint and new # cols
  17. onBreakpointChange: (newBreakpoint: string, newCols: number) => void,
  18. // Callback so you can save the layout.
  19. // AllLayouts are keyed by breakpoint.
  20. onLayoutChange: (currentLayout: Layout, allLayouts: {[key: $Keys<breakpoints>]: Layout}) => void,
  21. // Callback when the width changes, so you can modify the layout as needed.
  22. onWidthChange: (containerWidth: number, margin: [number, number], cols: number, containerPadding: [number, number]) => void;

Grid Item Props

RGL supports the following properties on grid items or layout items. When initializing a grid,
build a layout array (as in the first example above), or attach this object as the data-grid property
to each of your child elements (as in the second example).

If data-grid is provided on an item, it will take precedence over an item in the layout with the same key (i).

Note that if a grid item is provided but incomplete (missing one of x, y, w, or h), an error
will be thrown so you can correct your layout.

If no properties are provided for a grid item, one will be generated with a width and height of 1.

You can set minimums and maximums for each dimension. This is for resizing; it of course has no effect if resizing
is disabled. Errors will be thrown if your mins and maxes overlap incorrectly, or your initial dimensions
are out of range.

Any <GridItem> properties defined directly will take precedence over globally-set options. For
example, if the layout has the property isDraggable: false, but the grid item has the prop isDraggable: true, the item
will be draggable, even if the item is marked static: true.

  1. {
  2. // A string corresponding to the component key
  3. i: string,
  4. // These are all in grid units, not pixels
  5. x: number,
  6. y: number,
  7. w: number,
  8. h: number,
  9. minW: ?number = 0,
  10. maxW: ?number = Infinity,
  11. minH: ?number = 0,
  12. maxH: ?number = Infinity,
  13. // If true, equal to `isDraggable: false, isResizable: false`.
  14. static: ?boolean = false,
  15. // If false, will not be draggable. Overrides `static`.
  16. isDraggable: ?boolean = true,
  17. // If false, will not be resizable. Overrides `static`.
  18. isResizable: ?boolean = true,
  19. // By default, a handle is only shown on the bottom-right (southeast) corner.
  20. // As of RGL >= 1.4.0, resizing on any corner works just fine!
  21. resizeHandles?: ?Array<'s' | 'w' | 'e' | 'n' | 'sw' | 'nw' | 'se' | 'ne'> = ['se']
  22. // If true and draggable, item will be moved only within grid.
  23. isBounded: ?boolean = false
  24. }

Grid Item Heights and Widths

Grid item widths are based on container and number of columns. The size of a grid unit’s height is based on rowHeight.

Note that an item that has h=2 is not exactly twice as tall as one with h=1 unless you have no margin!

In order for the grid to not be ragged, when an item spans grid units, it must also span margins. So you must add the height or width or the margin you are spanning for each unit. So actual pixel height is (rowHeight * h) + (marginH * (h - 1).

For example, with rowHeight=30, margin=[10,10] and a unit with height 4, the calculation is (30 * 4) + (10 * 3)

margin

If this is a problem for you, set margin=[0,0] and handle visual spacing between your elements inside the elements’ content.

Performance

<ReactGridLayout> has an optimized shouldComponentUpdate implementation, but it relies on the user memoizing the children array:

  1. // lib/ReactGridLayout.jsx
  2. // ...
  3. shouldComponentUpdate(nextProps: Props, nextState: State) {
  4. return (
  5. // NOTE: this is almost always unequal. Therefore the only way to get better performance
  6. // from SCU is if the user intentionally memoizes children. If they do, and they can
  7. // handle changes properly, performance will increase.
  8. this.props.children !== nextProps.children ||
  9. !fastRGLPropsEqual(this.props, nextProps, isEqual) ||
  10. !isEqual(this.state.activeDrag, nextState.activeDrag)
  11. );
  12. }
  13. // ...

If you memoize your children, you can take advantage of this, and reap faster rerenders. For example:

  1. function MyGrid(props) {
  2. const children = React.useMemo(() => {
  3. return new Array(props.count).fill(undefined).map((val, idx) => {
  4. return <div key={idx} data-grid={{ x: idx, y: 1, w: 1, h: 1 }} ></div>;
  5. });
  6. }, [props.count]);
  7. return <ReactGridLayout cols={12}>{children}</ReactGridLayout>;
  8. }

Because the children prop doesn’t change between rerenders, updates to <MyGrid> won’t result in new renders, improving performance.

React Hooks Performance

Using hooks to save your layout state on change will cause the layouts to re-render as the ResponsiveGridLayout will change it’s value on every render.
To avoid this you should wrap your WidthProvider in a useMemo:

  1. const ResponsiveReactGridLayout = useMemo(() => WidthProvider(Responsive), []);

Custom Child Components and Draggable Handles

If you use React Components as grid children, they need to do a few things:

  1. Forward refs to an underlying DOM node, and
  2. Forward style,className, onMouseDown, onMouseUp and onTouchEnd to that same DOM node.

For example:

  1. const CustomGridItemComponent = React.forwardRef(({style, className, onMouseDown, onMouseUp, onTouchEnd, children, ...props}, ref) => {
  2. return (
  3. <div style={{ /* styles */, ...style}} className={className} ref={ref} onMouseDown={onMouseDown} onMouseUp={onMouseUp} onTouchEnd={onTouchEnd}>
  4. {/* Some other content */}
  5. {children} {/* Make sure to include children to add resizable handle */}
  6. </div>
  7. );
  8. })

The same is true of custom elements as draggable handles using the draggableHandle prop. This is so that
the underlying react-draggable library can get a reference to the DOM node underneath, manipulate
positioning via style, and set classes.

Contribute

If you have a feature request, please add it as an issue or make a pull request.

If you have a bug to report, please reproduce the bug in CodeSandbox to help
us easily isolate it.

TODO List

  • Basic grid layout
  • Fluid grid layout
  • Grid packing
  • Draggable grid items
  • Live grid packing while dragging
  • Resizable grid items
  • Layouts per responsive breakpoint
  • Define grid attributes on children themselves (data-grid key)
  • Static elements
  • Persistent id per item for predictable localstorage restores, even when # items changes
  • Min/max w/h per item
  • Resizable handles on other corners
  • Configurable w/h per breakpoint