### Install gridjs-react Source: https://gridjs.io/docs/examples/react-cells Install the React wrapper library for Grid.js using npm. ```bash npm install gridjs-react --save ``` -------------------------------- ### Install Grid.js with NPM Source: https://gridjs.io/docs/install Install the Grid.js package using NPM. This command also installs all necessary dependencies. ```bash npm install gridjs --save ``` -------------------------------- ### Install Grid.js Svelte Wrapper Source: https://gridjs.io/docs/integrations/svelte Install the necessary packages for the Grid.js Svelte wrapper using npm. ```bash npm install gridjs gridjs-svelte ``` -------------------------------- ### Install Vue.js Integration Source: https://gridjs.io/docs/integrations/laravel Install the necessary Vue.js integration for the DataGrid package. ```bash npm install gridjs-vue ``` -------------------------------- ### Browser HTML Setup Source: https://gridjs.io/docs/hello-world Include Grid.js CSS and JS files directly in your HTML to use it without build tools. ```html
``` -------------------------------- ### Initialize Grid with Data and Columns Source: https://gridjs.io/docs/examples/hello-world Use this snippet to create a new Grid.js instance with predefined columns and data. This is the most common way to start using Grid.js. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); ``` -------------------------------- ### Install Laravel DataGrid Package Source: https://gridjs.io/docs/integrations/laravel Install the Laravel DataGrid package using Composer. ```bash composer require wdev-rs/laravel-datagrid ``` -------------------------------- ### Install Grid.js and Angular Plugin Source: https://gridjs.io/docs/integrations/angular Install the necessary packages using npm. This includes the core Grid.js library and the Angular integration package. ```bash npm install gridjs gridjs-angular ``` -------------------------------- ### React Integration Example Source: https://gridjs.io/docs/hello-world Demonstrates how to import and initiate Grid.js within a React functional component using `useRef` and `useEffect`. ```javascript import { Grid } from "gridjs"; import "gridjs/dist/theme/mermaid.css"; function helloWorld () { const wrapperRef = useRef(null); const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); useEffect(() => { grid.render(wrapperRef.current); }); return
; } ``` -------------------------------- ### Import Grid.js in Node.js Source: https://gridjs.io/docs/install Import the Grid component and the mermaid CSS theme after installing via NPM. ```javascript import { Grid } from "gridjs"; import "gridjs/dist/theme/mermaid.css"; ``` -------------------------------- ### Subscribe to Row Selection Events Source: https://gridjs.io/docs/plugins/selection/selection-events Subscribe to the `RowSelection` store to get updates when rows are selected or deselected. This example shows how to initialize the grid with a selection plugin and then subscribe to the store's events. ```javascript const grid = new Grid({ columns: [ { id: 'awesomeCheckbox', name: 'Select', plugin: { component: RowSelection } }, { name: 'Name', formatter: (cell) => `Name: ${cell}` }, 'Email', ], sort: true, data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), ]) }); // subscribe to the store events grid.config.store.subscribe(function (state) { console.log('checkbox updated', state.rowSelection); }) ``` -------------------------------- ### Install gridjs-jquery using NPM Source: https://gridjs.io/docs/integrations/jquery Install the gridjs-jquery package via npm. This package includes Grid.js itself, so no separate installation is needed. ```bash npm install --save gridjs-jquery ``` -------------------------------- ### Server-side Search Integration Source: https://gridjs.io/docs/server-side Configure the search plugin to perform server-side searches. This example shows how to dynamically append the search keyword to the base URL. ```javascript search: { server: { url: (prev, keyword) => `${prev}?search=${keyword}` } } ``` -------------------------------- ### Configure Pagination Limit Source: https://gridjs.io/docs/examples/pagination Customize the pagination by setting a specific `limit` within the `pagination` configuration object. This example sets the limit to 1 item per page. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], pagination: { limit: 1 }, data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); ``` -------------------------------- ### Set Initial Width with Resizable Columns Source: https://gridjs.io/docs/examples/resizable You can specify an initial overall width for the grid using the `width` option before enabling `resizable: true`. This sets a starting point for column resizing. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ], width: 500, resizable: true }); ``` -------------------------------- ### Dynamic Data Grid Example Source: https://gridjs.io/docs/integrations/react A React component demonstrating a Grid.js table with dynamically added records. It uses faker.js for generating sample data and useState for managing the data array. ```javascript function MyComponent(props) { const row = () => [faker.name.findName(), faker.internet.email()]; const [data, setData] = useState([row()]); const update = () => { setData(data.slice(0).concat([row()])); } return (
); } ``` -------------------------------- ### Basic Grid Usage Source: https://gridjs.io/docs/integrations/react Render a basic Grid.js table in React by passing data, columns, and configuration options to the Grid component. This example includes search and pagination. ```javascript ``` -------------------------------- ### Basic Wide Table Configuration Source: https://gridjs.io/docs/examples/wide-table This snippet demonstrates the basic setup for a wide table in Grid.js. It defines columns, enables sorting and pagination, and populates the table with data. This is suitable for tables with many columns where content might naturally extend horizontally. ```javascript const grid = new Grid({ columns: [ 'Name', 'Email', 'Title', 'Company', 'Country', 'County', ], sort: true, pagination: true, data: Array(50).fill().map(x => [ faker.name.findName(), faker.internet.email(), faker.name.title(), faker.company.companyName(), faker.address.country(), faker.address.county(), ]) }); ``` -------------------------------- ### POST Method for Server-side Fetching Source: https://gridjs.io/docs/server-side Change the default HTTP GET method to POST for server-side data requests by using the `method` property within the `server` configuration. ```javascript const grid = new Grid({ server: { method: 'POST', // ... } }); ``` -------------------------------- ### Render React Components in Grid.js Source: https://gridjs.io/docs/examples/react-cells Example demonstrating how to use React components for cell formatting and action buttons within a Grid.js table. This includes formatting email cells with italicized text and adding an editable button to action cells. ```javascript const grid = new Grid({ columns: [ 'Name', { name: 'Email', formatter: (cell) => _({cell}) }, 'Actions' ], data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), _() ]) }); ``` -------------------------------- ### Grid.js Plugin with Angular Component Source: https://gridjs.io/docs/integrations/angular Example of creating a Grid.js plugin using Angular's `h` function for rendering custom content within the grid. ```typescript { id: 'myplugin', component: h(() => h('h1', {}, 'Hello world!'), {}), position: PluginPosition.Header, } ``` -------------------------------- ### Connect Custom Component to Grid.js Source: https://gridjs.io/docs/examples/virtual-dom Integrate a custom Preact component into Grid.js by using it within the data mapping. This example renders bolded email addresses in the 'Email' column. ```javascript function bold(text) { return h('b', {}, text); } const grid = new Grid({ columns: [ 'Name', 'Email' ], data: Array(5).fill().map(x => [ faker.name.findName(), bold(faker.internet.email()) ]) }); ``` -------------------------------- ### Basic Grid.js Vue Component Usage Source: https://gridjs.io/docs/integrations/vue Implement a basic Grid.js table in a Vue component by passing column headers and row data. This example demonstrates the fundamental way to display data using gridjs-vue. ```html ``` -------------------------------- ### Create a Custom Preact Component Source: https://gridjs.io/docs/examples/virtual-dom Define a custom Preact component function that utilizes the 'h' function to create virtual DOM elements. This example creates a 'bold' component. ```javascript function bold(text) { return h('b', {}, text); } ``` -------------------------------- ### Calculate and Format Cell Based on Row Data Source: https://gridjs.io/docs/examples/cell-formatting Use the 'formatter' property to access data from other cells in the same row for calculations. The example sums 'Salary 1' and 'Salary 2' and formats the result. ```javascript const grid = new Grid({ columns: [ 'Salary 1', 'Salary 2', { name: 'Sum', data: null, formatter: (_, row) => `$${(row.cells[0].data + row.cells[1].data).toLocaleString()} USD` }, ], data: Array(5).fill().map(x => [ Math.round(Math.random() * 100000), Math.round(Math.random() * 100000) ]) }); ``` -------------------------------- ### Wide Table with nowrap Styling Source: https://gridjs.io/docs/examples/wide-table This example shows how to configure Grid.js for wide tables by applying `white-space: nowrap` to the table element. This prevents text from wrapping, ensuring all content remains on a single line and contributing to the table's width. It's useful when you want to maintain the integrity of long text entries without line breaks. ```javascript const grid = new Grid({ columns: [ 'Name', 'Email', 'Title', 'Company', 'Country', 'County', ], style: { table: { 'white-space': 'nowrap' } }, sort: true, pagination: true, data: Array(50).fill().map(x => [ faker.name.findName(), faker.internet.email(), faker.name.title(), faker.company.companyName(), faker.address.country(), faker.address.county(), ]) }); ``` -------------------------------- ### Install Row Selection Plugin Source: https://gridjs.io/docs/plugins/selection/row-selection Add a new column to your Grid.js configuration to enable row selection. This column will contain the checkboxes for selecting rows. The 'Email' column is used as the row identifier in this example. ```javascript const grid = new Grid({ columns: [ { id: 'myCheckbox', name: 'Select', plugin: { // install the RowSelection plugin component: RowSelection, } }, { name: 'Name', formatter: (cell) => `Name: ${cell}` }, 'Email', ], sort: true, search: true, data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), ]) }); ``` -------------------------------- ### Initialize and Update Grid.js with updateConfig Source: https://gridjs.io/docs/config Create an empty Grid.js instance and then use the updateConfig method to set its initial configuration, including columns and data. ```javascript new Grid().updateConfig({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); ``` -------------------------------- ### Initialize Grid.js with Constructor Source: https://gridjs.io/docs/config Use the Grid constructor to pass an initial configuration object, including columns and data, when creating a new Grid.js instance. ```javascript new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); ``` -------------------------------- ### Initialize Grid.js from an HTML Table Source: https://gridjs.io/docs/config/from Use the 'from' option to specify the HTML table element to use as the data source. This is an optional configuration. ```javascript new gridjs.Grid({ from: document.getElementById('myTable') }).render(); ``` -------------------------------- ### Hide a Column in Grid.js Source: https://gridjs.io/docs/examples/hidden-columns Add `hidden: true` to a column's definition to hide it from the grid. This example demonstrates hiding the 'Name' column. ```javascript const grid = new Grid({ columns: [ { name: 'Name', hidden: true }, 'Email', 'Title', ], sort: true, pagination: true, data: Array(50).fill().map(x => [ faker.name.findName(), faker.internet.email(), faker.name.title(), ]) }); ``` -------------------------------- ### Initialize Grid.js with jQuery Source: https://gridjs.io/docs/integrations/jquery Select an HTML element with a jQuery selector and call the Grid constructor to initialize Grid.js with specified columns and data. ```javascript $("div#wrapper").Grid({ columns: ['Name', 'Age', 'Email'], data: [ ['John', 25, 'john@k.com'], ['Mark', 59, 'mark@e.com'], // ... ], }); ``` -------------------------------- ### Link Grid.js Mermaid Theme CSS via unpkg Source: https://gridjs.io/docs/install Link the mermaid theme CSS file for Grid.js from unpkg. ```html ``` -------------------------------- ### Enable Basic Pagination Source: https://gridjs.io/docs/config/pagination Configure the number of rows per page and hide the pagination summary. Use this for client-side pagination. ```javascript new Grid({ data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'], ['Eoin', 'eo3n@yahoo.com', '(05) 10 878 5554'], ['Nisen', 'nis900@gmail.com', '313 333 1923'] ], pagination: { limit: 2, summary: false } }); ``` -------------------------------- ### Initialize Grid with Multi-Column Sort Enabled Source: https://gridjs.io/docs/examples/multi-sort This snippet shows how to initialize a Grid.js instance with multi-column sorting enabled. Ensure the 'sort' option is set to true. Users can then hold 'shift' and click headers to sort. ```javascript const grid = new Grid({ columns: [ 'Name', 'Age', 'Email', ], sort: true, data: [ ['Mark', 25, 'john@example.com'], ['Nancy', 25, 'n99@gmail.com'], ['Eoin', 55, 'eo3n@yahoo.com'], ['Nisen', 60, 'nis900@gmail.com'] ] }); ``` -------------------------------- ### Import RowSelection Plugin (CDN - UMD) Source: https://gridjs.io/docs/plugins/selection Include the Selection plugin via a CDN link to access the UMD format. ```html ``` -------------------------------- ### Basic Svelte Grid Component Usage Source: https://gridjs.io/docs/integrations/svelte Demonstrates how to import and use the Grid component in a Svelte application. Ensure to import the Grid.js CSS theme for proper styling. ```svelte ``` -------------------------------- ### Ordering Plugins in Grid.js Source: https://gridjs.io/docs/plugins/basics Illustrates how to control the rendering order of plugins within the same position using the optional 'order' property in the plugin.add() method. Lower numbers render first. ```javascript grid.plugin.add({ id: 'myfirstplugin', component: MyPlugin, position: PluginPosition.Header, order: 1, }); grid.plugin.add({ id: 'mysecondplugin', component: MyPlugin, position: PluginPosition.Header, order: 2, }); ``` -------------------------------- ### Publish Vendor Files Source: https://gridjs.io/docs/integrations/laravel Publish the package's vendor files using the Artisan command. ```bash php artisan vendor:publish --provider="WdevRs\LaravelDatagrid\LaravelDatagridServiceProvider" ``` -------------------------------- ### Using html function for header cells Source: https://gridjs.io/docs/examples/html-header-cells Utilize the `html` function within the `columns` configuration to render custom HTML content in header cells. This example shows an italicized 'Name' and a styled 'Email' header. ```javascript const grid = new Grid({ columns: [ { id: 'name', name: html('Name'), }, { id: 'email', name: html('
Email
'), } ], data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), ]) }); ``` -------------------------------- ### Adding Plugins via React Wrapper Source: https://gridjs.io/docs/plugins/basics Shows how to integrate plugins into a Grid.js component when using the React wrapper. Plugins are provided as an array to the 'plugins' property. ```jsx ``` -------------------------------- ### Using h function for virtual DOM header cells Source: https://gridjs.io/docs/examples/html-header-cells Employ the `h` function to construct virtual DOM elements for header cells. This example renders a bold 'Name' and a styled 'Email' header using `h`. ```javascript const grid = new Grid({ columns: [ { id: 'name', name: h('b', {}, 'Name'), }, { id: 'div', name: h('div', { style: { border: '1px solid #ccc', padding: '5px', 'border-radius': '5px', 'text-align': 'center', } }, 'Email'), }, ], data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), ]), search: true }); ``` -------------------------------- ### Import Grid.js React Wrapper Source: https://gridjs.io/docs/examples/react-cells Import the '_' function from the gridjs-react package to enable React component rendering. ```javascript import { _ } from "gridjs-react"; ``` -------------------------------- ### Import Grid.js and Chartist Libraries Source: https://gridjs.io/docs/examples/stock-market Import necessary components from Grid.js and the Chartist library for chart rendering. ```javascript import { Grid, h, createRef as gCreateRef } from "gridjs"; import Chartist from 'chartist'; ``` -------------------------------- ### Extended Grid.js Vue Component Configuration Source: https://gridjs.io/docs/integrations/vue Configure advanced Grid.js options within a Vue component, including data sources (rows, from, server), and various features like pagination, search, and sorting. This example shows how to bind numerous Grid.js properties to Vue data properties. ```html ``` -------------------------------- ### Add a Plugin to Grid.js Source: https://gridjs.io/docs/plugins/writing-plugin Instantiate a Grid.js instance and add your custom plugin to the header. ```javascript function MyPlugin () { return h('h1', {}, 'Hello World!'); } const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'], ] }); grid.plugin.add({ id: 'myplugin', component: MyPlugin, position: PluginPosition.Header, }); ``` -------------------------------- ### Full Configuration with Server-side Search Source: https://gridjs.io/docs/server-side Combines server-side data fetching with server-side search functionality. The search plugin refines the base URL with the user's keyword. ```javascript const grid = new Grid({ search: { server: { url: (prev, keyword) => `${prev}?search=${keyword}` } }, columns: ['Title', 'Director', 'Producer'], server: { url: 'https://swapi.dev/api/films/', then: data => data.results.map(movie => [movie.title, movie.director, movie.producer]) } }); ``` -------------------------------- ### Link Grid.js Mermaid Theme CSS via jsdelivr Source: https://gridjs.io/docs/install Link the mermaid theme CSS file for Grid.js from the jsdelivr CDN. ```html ``` -------------------------------- ### Enable Pagination Source: https://gridjs.io/docs/examples/pagination Enable default pagination by setting `pagination: true` in the Grid configuration. This will use the default limit of 10 items per page. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], pagination: true, data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }); ``` -------------------------------- ### Update Grid Configuration Source: https://gridjs.io/docs/examples/hello-world This snippet shows how to update an existing Grid.js instance's configuration, specifically adding column definitions after initial data loading. Useful for dynamic updates. ```javascript const grid = new Grid({ data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ] }).updateConfig({ columns: ['Name', 'Email', 'Phone Number'], }); ``` -------------------------------- ### Adding a Plugin to Grid.js Instance Source: https://gridjs.io/docs/plugins/basics Demonstrates how to add a custom plugin to a Grid.js instance using the plugin.add() method. The 'id', 'component', and 'position' are mandatory fields. ```javascript grid.plugin.add({ id: 'myplugin', component: MyPlugin, position: PluginPosition.Header, }); ``` -------------------------------- ### Browser JavaScript Initialization Source: https://gridjs.io/docs/hello-world Instantiate the Grid.js Grid class in your JavaScript file to render a table. ```javascript new gridjs.Grid({ columns: ["Name", "Email", "Phone Number"], data: [ ["John", "john@example.com", "(353) 01 222 3333"], ["Mark", "mark@gmail.com", "(01) 22 888 4444"], ["Eoin", "eoin@gmail.com", "0097 22 654 00033"], ["Sarah", "sarahcdd@gmail.com", "+322 876 1233"], ["Afshin", "afshin@mail.com", "(353) 22 87 8356"] ] }).render(document.getElementById("wrapper")); ``` -------------------------------- ### Render DataGrid with Custom View Source: https://gridjs.io/docs/integrations/laravel Render the DataGrid in a controller using a custom view. Pass the desired view name to the 'render' method. ```php public function index(CategoriesDataGrid $dataGrid, Request $request) { return $dataGrid->render('admin.common.index'); } ``` -------------------------------- ### Render Default DataGrid View Source: https://gridjs.io/docs/integrations/laravel Render the DataGrid in a controller using the default view. The 'render' method without arguments uses the default view path. ```php public function index(CategoriesDataGrid $dataGrid, Request $request) { return $dataGrid->render(); } ``` -------------------------------- ### Enable Server-Side Search Source: https://gridjs.io/docs/examples/server-side-search Configure the `server` option within the `search` definition to enable server-side search. The `url` function is used to construct the search query URL based on the previous URL and the search keyword. The `server.url` and `server.then` options are used to fetch and process data from the API. ```javascript const grid = new Grid({ pagination: true, search: { server: { url: (prev, keyword) => `${prev}?search=${keyword}` } }, columns: ['Title', 'Director', 'Producer'], server: { url: 'https://swapi.dev/api/films/', then: data => data.results.map(movie => [movie.title, movie.director, movie.producer]) } }); ``` -------------------------------- ### Include Grid.js UMD Format via unpkg Source: https://gridjs.io/docs/install Include the UMD (Universal Module Definition) format of Grid.js directly via a script tag from unpkg. ```html ``` -------------------------------- ### Import Emotion for CSS-in-JS Source: https://gridjs.io/docs/examples/css-in-js Import the 'css' function from the '@emotion/css' library to enable CSS-in-JS styling. ```javascript import { css } from '@emotion/css'; ``` -------------------------------- ### Basic Server-side Data Fetching Source: https://gridjs.io/docs/server-side Configure the Grid.js instance to pull data from a server API. Specify the data source URL and a `then` function to parse the results. ```javascript const grid = new Grid({ columns: ['Title', 'Director', 'Producer'], server: { url: 'https://swapi.dev/api/films/', then: data => data.results.map(movie => [movie.title, movie.director, movie.producer] ) } }); ``` -------------------------------- ### Async Data Loading with Promise and setTimeout Source: https://gridjs.io/docs/examples/import-async Use an async function with `Promise` and `setTimeout` to simulate fetching data after a delay. This is useful for external HTTP calls. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: () => { return new Promise(resolve => { setTimeout(() => resolve([ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ]), 1000); }); } }); ``` -------------------------------- ### Define a Plugin using JSX Source: https://gridjs.io/docs/plugins/writing-plugin Alternatively, use JSX syntax to define your plugin component if your bundler supports Preact JSX. ```javascript function MyPlugin () { return

Hello World!

; } ``` -------------------------------- ### Node.js Module Import Source: https://gridjs.io/docs/hello-world Import Grid.js and its theme CSS when using it as a Node.js module. ```javascript import { Grid } from "gridjs"; import "gridjs/dist/theme/mermaid.css"; ``` -------------------------------- ### Enable Basic Search in Grid.js Source: https://gridjs.io/docs/config/search Enable the global search plugin by setting the `search` option to `true` in the Grid.js configuration. This is the simplest way to add search functionality to your grid. ```javascript new Grid({ data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'], ['Eoin', 'eo3n@yahoo.com', '(05) 10 878 5554'], ['Nisen', 'nis900@gmail.com', '313 333 1923'] ], search: true }); ``` -------------------------------- ### Using html function in Data and Formatters Source: https://gridjs.io/docs/examples/html-cells Demonstrates using the `html` function to format cell data and create custom cell content, including links. ```javascript const grid = new Grid({ columns: [ { name: 'Name', formatter: (cell) => html(`${cell}`) }, 'Email', { name: 'Actions', formatter: (_, row) => html(`Email`) }, ], data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), null ]) }); ``` -------------------------------- ### Format Cell Content with HTML Source: https://gridjs.io/docs/examples/cell-formatting Demonstrates adding HTML content to cells. Refer to the 'Populating cells with HTML' documentation for more details. ```javascript const grid = new Grid({ columns: [ 'Name', 'Email' ], data: [ ['

Hello

', 'Link'] ] }); ``` -------------------------------- ### Import JSON with Explicit Column IDs Source: https://gridjs.io/docs/examples/import-json Use this when you need to explicitly define column IDs that match your JSON keys. Ensure each column has a unique 'id'. ```javascript const grid = new Grid({ columns: [{ id: 'name', name: 'Name' }, { id: 'email', name: 'Email' }, { id: 'phoneNumber', name: 'Phone Number' }], data: [ { name: 'John', email: 'john@example.com', phoneNumber: '(353) 01 222 3333' }, { name: 'Mark', email: 'mark@gmail.com', phoneNumber: '(01) 22 888 4444' }, ] }); ``` -------------------------------- ### Include Grid.js UMD Format via jsdelivr Source: https://gridjs.io/docs/install Include the UMD format of Grid.js using a script tag from the jsdelivr CDN. ```html ``` -------------------------------- ### Load Data from HTML Table with React Source: https://gridjs.io/docs/examples/from Use this snippet to initialize Grid.js from an existing HTML table within a React component. Ensure the table element and the grid container have refs assigned. ```javascript function () { const tableRef = useRef(null); const wrapperRef = useRef(null); useEffect(() => { const grid = new Grid({ from: tableRef.current, }).render(wrapperRef.current); }); return ( <>
Name Email
John john@example.com
Mike mike@example.com
); } ``` -------------------------------- ### Custom HTTP Client with XMLHttpRequest Source: https://gridjs.io/docs/examples/custom-http-client Implement a custom HTTP client using `XMLHttpRequest` to fetch data for Grid.js. This approach allows you to control the request and response handling, ensuring the output conforms to the `StorageResponse` format. ```javascript const grid = new Grid({ columns: ['Name', 'Language', 'Released At', 'Artist'], server: { url: 'https://api.scryfall.com/cards/search?q=Inspiring', data: (opts) => { return new Promise((resolve, reject) => { // let's implement our own HTTP client const xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4) { if (this.status === 200) { const resp = JSON.parse(this.response); // make sure the output conforms to StorageResponse format: // https://github.com/grid-js/gridjs/blob/master/src/storage/storage.ts#L21-L24 resolve({ data: resp.data.map(card => [card.name, card.lang, card.released_at, card.artist]), total: resp.total_cards, }); } else { reject(); } } }; xhttp.open("GET", opts.url, true); xhttp.send(); }); } }, pagination: { limit: 5 } }); ``` -------------------------------- ### Import Server-Side Data Source: https://gridjs.io/docs/examples/server Use the `server` property to load data from a remote URL and process it using the `then` function. This is useful for populating tables with dynamic content from an API. ```javascript const grid = new Grid({ columns: ['Name', 'Language', 'Released At', 'Artist'], server: { url: 'https://api.scryfall.com/cards/search?q=Inspiring', then: data => data.data.map(card => [card.name, card.lang, card.released_at, card.artist]) } }); ``` -------------------------------- ### Enable Sorting for All Columns Source: https://gridjs.io/docs/config/sort To enable sorting for all columns in the grid, set the 'sort' configuration option to true. ```javascript new Grid({ data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'], ['Eoin', 'eo3n@yahoo.com', '(05) 10 878 5554'], ['Nisen', 'nis900@gmail.com', '313 333 1923'] ], sort: true }); ``` -------------------------------- ### Rendering HTML in a Cell with Styling Source: https://gridjs.io/docs/examples/html-cells Shows how to render custom HTML content with inline styling directly within a data cell. Be cautious of XSS attacks and sanitize inputs. ```javascript const grid = new Grid({ columns: [ 'Name', 'Email', 'Actions', ], data: Array(5).fill().map(x => [ faker.name.findName(), faker.internet.email(), html( "
" + "
hello!
" + "
" ) ]), search: true }); ``` -------------------------------- ### Async Data Fetching with Loading State Source: https://gridjs.io/docs/examples/loading-state Use an async function for the 'data' option to enable the loading state. The loading bar appears while the promise resolves. This is useful for simulating XHR calls to a server. ```javascript const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], sort: true, search: true, data: () => { return new Promise(resolve => { setTimeout(() => resolve([ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'] ]), 2000); }); } }); ``` -------------------------------- ### Include jQuery and gridjs-jquery via CDN Source: https://gridjs.io/docs/integrations/jquery Include these scripts and the stylesheet in your HTML's head tag to use the jQuery wrapper. ```html ``` -------------------------------- ### Server-Side Pagination Configuration Source: https://gridjs.io/docs/examples/server-side-pagination Configure Grid.js for server-side pagination by specifying the server URL and data transformation. The `total` property is crucial for the pagination to function correctly. ```javascript const grid = new Grid({ columns: ['Pokemon', 'URL'], pagination: { limit: 5, server: { url: (prev, page, limit) => `${prev}?limit=${limit}&offset=${page * limit}` } }, server: { url: 'https://pokeapi.co/api/v2/pokemon', then: data => data.results.map(pokemon => [ pokemon.name, html(`Link to ${pokemon.name}`) ]), total: data => data.count } }); ``` -------------------------------- ### Include Grid.js ES Module in Browser via unpkg Source: https://gridjs.io/docs/install Include Grid.js as an ES module from unpkg. This method allows importing specific components like Grid and html. ```html ``` -------------------------------- ### Advanced Column Definition with TColumn Objects Source: https://gridjs.io/docs/config/columns Configure columns with detailed properties like sorting and width using TColumn objects. ```javascript new Grid({ columns: [{ name: "Name", sort: true, }, { name: "Email" }, { name: "Phone Number", width: '50%' }] }); ``` -------------------------------- ### Import RowSelection Plugin (ES Module) Source: https://gridjs.io/docs/plugins/selection Import the RowSelection plugin using ES module syntax for use in your project. ```javascript import { RowSelection } from "gridjs/plugins/selection"; ``` -------------------------------- ### Importing a Locale Source: https://gridjs.io/docs/localization/locales Import a specific language file from the gridjs/l10n module. This is the first step to enable localization. ```javascript import { frFR } from "gridjs/l10n"; ``` -------------------------------- ### Importing html function Source: https://gridjs.io/docs/examples/html-header-cells Import the `html` function from the gridjs library to enable HTML rendering in header cells. ```javascript import { Grid, html } from "gridjs"; ``` -------------------------------- ### Convert HTML Table to Grid.js with jQuery Source: https://gridjs.io/docs/integrations/jquery Select an HTML table using a jQuery selector and call the Grid function to convert it into a Grid.js instance. All Grid.js configurations can be passed. ```javascript $("table#myTable").Grid(); ``` -------------------------------- ### Server-Side Data Loading with Fetch API Source: https://gridjs.io/docs/config/server Configure Grid.js to fetch data from a remote URL. Use the 'server' option with 'url', 'then', and 'handle' for custom data processing and response handling. ```javascript new Grid({ columns: ['Name', 'Language', 'Released At', 'Artist'], server: { url: 'https://api.scryfall.com/cards/search?q=Inspiring', then: data => data.data.map(card => [card.name, card.lang, card.released_at, card.artist]), handle: (res) => { // no matching records found if (res.status === 404) return {data: []}; if (res.ok) return res.json(); throw Error('oh no :('); }, } }); ``` -------------------------------- ### Grid.js Column Formatter with HTML Source: https://gridjs.io/docs/integrations/angular Demonstrates using the `html` function within a column formatter to render HTML content, such as a mailto link, based on row data. ```typescript { name: 'Email', formatter: (_, row) => html( `${row.cells[1].data}` ) } ``` -------------------------------- ### Parse XML with Grid.js Server Handler Source: https://gridjs.io/docs/examples/import-xml Use this configuration to fetch XML data from a URL and parse it using the DOMParser. The 'handle' function intercepts the response, and the 'then' function processes the parsed XML. ```javascript const grid = new Grid({ sort: true, search: true, pagination: true, columns: ['Location', 'Change Frequency', 'Priority'], server: { url: 'https://gridjs.io/sitemap.xml', handle: (res) => { return res.text().then(str => (new window.DOMParser()).parseFromString(str, "text/xml")); }, then: data => { return Array.from(data.querySelectorAll('url')) .map(row => [ row.querySelector('loc').innerHTML, row.querySelector('changefreq').innerHTML, row.querySelector('priority').innerHTML, ]); } } }); ``` -------------------------------- ### Default Grid.js Options for Vue Source: https://gridjs.io/docs/integrations/vue View the default configuration options for the Grid.js Vue component. These settings are applied if not explicitly overridden in your component. ```json { "autoWidth": true, "cols": [""], "from": undefined, "language": undefined, "pagination": false, "rows": undefined, "search": false, "server": undefined, "sort": false, "theme": "mermaid", "width": "100%" } ``` -------------------------------- ### Import h from Grid.js Source: https://gridjs.io/docs/examples/virtual-dom Import the 'h' function from the 'gridjs' package to enable Preact's Virtual DOM rendering. ```javascript import { h } from "gridjs"; ``` -------------------------------- ### Update Grid.js Config and Force Render Source: https://gridjs.io/docs/examples/force-render Use `updateConfig()` to modify the grid's settings and `forceRender()` to apply changes. This is useful for dynamically updating table data or features after initial rendering. ```javascript function () { const wrapper = useRef(null); useEffect(() => { // initial setup const grid = new Grid({ columns: ['Name', 'Email', 'Phone Number'], data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ] }).render(wrapper.current); setTimeout(() => { // lets update the config grid.updateConfig({ search: true, data: [ ['John', 'john@example.com', '(353) 01 222 3333'], ['Mark', 'mark@gmail.com', '(01) 22 888 4444'], ] }).forceRender(); }, 2000); }, []); return (
); } ``` -------------------------------- ### Define Table Data with Array of Objects Source: https://gridjs.io/docs/config/data Provide data as an array of objects for easier column mapping by property name. Each object represents a row, with keys corresponding to column headers. ```javascript new Grid({ data: [ { name: 'John', email: 'john@example.com' }, { name: 'Mark', email: 'mark@gmail.com' }, { name: 'Eoin', email: 'eo3n@yahoo.com' }, { name: 'Nisen', email: 'nis900@gmail.com' } ] }); ```