[Table creation] A thorough explanation of how to use Grid.js!

ぶんけい

What is Grid.js - Dynamic table creation with JavaScript

Grid.js is a library of JavaScript that allows you to easily incorporate dynamic tables into your web pages. It is primarily used when you want to display data in a tabular format, and it has gained popularity for its flexibility and scalability. In particular, it is equipped with functions such as data sorting, filtering, and pagination, and is a major feature that can be easily implemented.

Advantages

  • Flexibility: Compatible with various data sources and easily customizable.
  • Scalability: Easily add features like sorting and filtering.
  • User-Friendly: Easy-to-read UI and intuitive navigation.

Usage Scenarios

  • Web pages and applications that require dynamic data representation
  • Create reports and dashboards
  • Data Management System

Basic Code Examples

Basic table creation with Grid.js
const grid = new Grid({
data: [
["John", 30, "Engineer"],
["Jane", 25, "Designer"]
],
columns: ["Name", "Age", "Occupation"]
});

grid.render(document.getElementById("wrapper"));

This code creates a simple table with columns for name, age, and occupation, and renders it into the HTML element you specify. Grid.js is very useful in web development because it provides powerful features in such short code.

Setting up the Grid.js - How to get started and basic setup

To be able to easily create dynamic tables using Grid.js, you first need to set it up. Here's how to install the Grid.js and how to create a basic table.

Installing the Grid.js

Grid.js can be easily installed through npm. Just run the following command:

npm install gridjs

Alternatively, you can use a CDN to load directly in your browser.

<pre class="prism line-numbers lang-js" data-lang="JavaScript"><script src="https://cdn.jsdelivr.net/npm/gridjs@latest/dist/gridjs.production.min.js"></ script>

Creating a basic table

To create your first table using Grid.js, follow these steps:

  1. Create a container to display the table in HTML.

    <pre class="prism line-numbers lang-html" data-lang="HTML"><div id="wrapper"></div>
  2. Create an instance of the Grid.js in JavaScript and set up the data and columns.

    const grid = new Grid({
    data: [
    ["John", 30, "Engineer"],
    ["Jane", 25, "Designer"]
    ],
    columns: ["Name", "Age", "Occupation"]
    });
  3. Render the instance to display the table.

    grid.render(document.getElementById("wrapper"));
    

Now the basic table will appear on the web page. This process is quite simple yet customizable, allowing you to display a variety of data effectively.

Customize tables - Enhance appearance and functionality

Grid.js makes it easy to customize the appearance and functionality of your table. Here, we'll show you how to apply styling options and customize columns and rows.

Styling options

Grid.js allows you to change the style of the table at will. You can use CSS to apply your own design or use an existing theme. Here's an example of applying custom CSS:

.gridjs-table {
border: 1px solid #ddd;
border-collapse: collapse;
}

.gridjs-th, .gridjs-td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}

Applying this code will change the table borders and cell padding to improve its appearance.

Column and row customization

You can also customize the display of columns and rows. For example, you can apply different styles based on conditions to certain columns.

const grid = new Grid({
columns: [
"Name",
{
name: "Age",
formatter: (cell) => cell > 30 ? `<span style="color:red;" >${cell}</span>` : cell
},
"Occupation"
],
data: [
["John", 35, "Engineer"],
["Jane", 25, "Designer"]
]
});

This code has customized it to appear in red when you are over 30 years old. Such a feature is very useful for making the data more intuitive.

advanced features - sort, search, pagination

Grid.js makes it easy to add advanced features to your table. This section focuses on sorting, filtering, and setting up pagination for data.

Sorting data

Sorting data greatly improves the convenience of tables. Grid.js allows you to sort by simply clicking on the column header.

const grid = new Grid({
columns: ["Name", "Age", "Occupation"],
sort: true,
data: [
["John", 35, "Engineer"],
["Jane", 25, "Designer"]
]
});

This code allows users to sort data in ascending or descending order based on any column.

Filtering

The filtering feature allows you to filter the data in the table based on specific criteria. This makes it possible to quickly find the information you need in a large amount of data.

grid.updateConfig({
search: true
}).forceRender();

The above code adds a search bar to the table, allowing users to enter keywords to narrow down the data.

Pagination

If you have a lot of data, pagination makes it easier to navigate the table. Grid.js makes it easy to set up pagination.

const grid = new Grid({
pagination: {
limit: 5
},
Other settings...
});

With this setup, the table only displays 5 rows of data at a time, and the rest of the data is split into other pages.

These advanced features can be invaluable when creating dynamic and interactive tables using Grid.js.

Advanced Options Combination - Practical Sample Code

Grid.js allows you to combine multiple advanced options to create more complex and dynamic tables. In this section, we'll explore sample code that combines sorting, filtering, and pagination, demonstrating how they work together.

Combined sample code

The code below combines multiple features of the Grid.js. It allows users to sort data, filter by specific criteria, and view data page by page.

const grid = new Grid({
search: true,
sort: true,
pagination: {
limit: 5
},
columns: ["Name", "Age", "Occupation"],
server: {
url: 'https://example.com/api/data',
then: data => data.map(item => [item.name, item.age, item.occupation])
}
});

This code example implements the following functionality:

  1. Search Functionality: Users can use the search bar at the top of the table to filter data instantly.

  2. Sorting Functionality: By clicking on the header of each column, you can sort the data based on that column in ascending or descending order.

  3. Pagination: Tables only display five rows of data at a time, and users can access other parts of the data using pagination controls.

  4. Server-side integration: Retrieve data from remote APIs and integrate it into tables.

In this way, Grid.js allows you to combine multiple advanced features to achieve a user-friendly representation of your data.

data integration and manipulation - incorporation of external data sources

Grid.js allows for data integration and interactive data manipulation from external data sources. In this section, we'll explain how to ingest data from external APIs and customize the user interactions that come with it.

Data integration from external APIs

Grid.js allows you to retrieve data from external APIs and incorporate it into tables. This is very useful for dynamic web applications and real-time data display.

const grid = new Grid({
server: {
url: 'https://example.com/api/data',
then: data => data.map(item => [item.name, item.age, item.occupation])
},
columns: ["Name", "Age", "Occupation"]
});

This code fetches the data from the URL you specify and displays it in a table. By using the then function, you can convert the retrieved data into a format suitable for the table.

Interactive Data Manipulation

It is also possible in Grid.js to allow users to interact directly with the data in the table. For example, you can view detailed information based on the click event of a row.

grid.on('rowClick', (row) => {
alert(`Clicked row: ${JSON.stringify(row.cells[0].data)}`);
});
This code alerts users when they

click on a row in the table, the data for that row. In this way, Grid.js allows you to closely integrate data and user interactions.

Event Handling - Dynamic User Interaction in Grid.js

Grid.js can accommodate user interactions on the table through event handling. In this section, we'll take a closer look at setting up event listeners and how to customize their behavior according to user events.

Setting up an event listener

One of the powerful features of Grid.js is the ability to easily set up listeners for different events. For example, you can define how a cell or row behaves when clicked.

grid.on('cellClick', (cell) => {
console.log(`Clicked cell: ${JSON.stringify(cell.data)}`);
});

In this example, when a user clicks on a cell, the data for that cell is displayed in the console. This makes it possible to perform specific actions depending on the user's actions.

Behavior in response to user events

Grid.js allows you to set up different responses based on user actions. For example, when a specific row is selected, you can display more information in a separate section.

grid.on('rowClick', (row) => {
document.getElementById('details').textContent = `Selected: ${JSON.stringify(row.cells.map(cell => cell.data))}`;
});

This code displays data from that row in a different part of the page when the user clicks on it. This allows the user to obtain detailed information, depending on the selection on the table.

Grid.js's event handling capabilities make table and user interactions richer and more meaningful.

Practical Examples >

To

enhance your understanding of Grid.js's applications, here are some real-world use cases: In this section, we'll look at how Grid.js can be applied in different scenarios and how it can improve the user experience.

Product list in the online shop

Online shops can use Grid.js to display product listings. Create tables with information such as product names, prices, and categories, making it easy for users to search and sort information.

const grid = new Grid({
columns: ["product name", "price", "category"],
server: {
url: 'https://example.com/api/products',
then: data => data.map(item => [item.name, item.price, item.category])
},
search: true,
sort: true
});

This table provides important information about products at a glance, allowing users to quickly find the right product for their needs.

Student Achievement Management for Educational Institutions

Educational institutions sometimes use Grid.js to manage student performance. Create tables with student names, subjects, grades, and more, allowing instructors to manage data efficiently.

const grid = new Grid({
columns: ["student's name", "subject", "grade"],
data: [
Data array...
],
pagination: {
limit: 10
},
sort: true
});

This table allows faculty to quickly identify trends in performance and plan responses to individual students as needed.

Conclusion

Grid.js is useful

in various scenarios due to its flexibility and scalability. It can be used for a wide range of applications, from product listings in online shops to grade management in educational institutions. Through these practical examples, it becomes clear how Grid.js can be useful in business and educational settings.

おすすめ記事

お問い合わせ

WEB制作、動画制作、オンライン配信、SNS運用代行などお気軽にご相談、お問い合わせください。

お問い合わせはこちら