GitHub reference https://github.com/react-grid-layout/react-grid-layout
React Grid layout supports responsive layout of components in the context. It only react without jQuery integrated.
Its feature:
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
- Compatibility with
<React.StrictMode>
How to install it:
npm install react-grid-layout
How to implement with NextJs app using typescript:
// Installation
// initualize nextjs project
npx create-next-app@latest
// install react-grid-layout
npm i --save-dev @types/react-grid-layout
Initialize code (base setup) of using react-grid-layout:
"use client";
import { useState } from "react";
import ReactGridLayout, { Layout } from "react-grid-layout";
import "react-grid-layout/css/styles.css"; // used to follow the style of react-grid-layout library
import "react-resizable/css/styles.css"; // used to do style when component is on resizing
export default function Home() {
const [layout, setLayout] = useState([
{ i: "a", x: 0, y: 0, w: 3, h: 2 },
{ i: "b", x: 1, y: 1, w: 3, h: 2 },
{ i: "c", x: 2, y: 2, w: 3, h: 2 },
]);
const handleLayoutChange = (newLayout: Layout[]) => {
setLayout(newLayout);
};
return (
<main>
<ReactGridLayout
className="layout"
layout={layout}
cols={12}
rowHeight={30}
width={1400}
autoSize
isResizable
transformScale={1}
useCSSTransforms
onLayoutChange={handleLayoutChange}
>
<div key="a">a</div>
<div key="b">b</div>
<div key="c">c</div>
</ReactGridLayout>
</main>
);
}
GridLayout was replaced by the
Note: All component’s width can be static of draggable, by just add a attribute more with layout.
{ i: "a", x: 0, y: 0, w: 3, h: 2, static:true },
If you want to resize all the angles we must be add one more attribute inside of ReactGridLayout tag:
resizeHandles={['se', 'sw', 'ne', 'nw']}
Note: Since the i variable in the layout is tied to the component key, it will still display by following the layout index even if the i variable’s index is not where the ordered components are.