0

In my REACT app I'm using npm package react-data-grid. On their website they provide an example of Column Reordering. I want to do exactly the same in my code.

I checked their source code but what I don't understand is how can I import all of the components they are using for columns reordering. Do I need to reimplement in my code all of the components they are using? Isn't a way to simply import them in my react app?

For example, for columns reordering, they are using the DraggableHeaderRenderer component. Is there a way to import this in my app instead of having all of its source code reproduced in my app?

gdv
  • 13
  • 3

1 Answers1

0

to use react-data-grid in your app, you need to import DraggableHeaderRenderer. I'll provide you a step-by-step.

  1. Install the react-data-grid package: npm install react-data-grid

  2. Import everything you need:

    import React from 'react'; import ReactDataGrid from 'react-data-grid'; import { DraggableHeader } from 'react-data-grid-addons';

  3. Define the data and columns for the grid.

  4. Create the main component that renders the data grid.

Here is full code:

import React from 'react';
import ReactDataGrid from 'react-data-grid';
import { DraggableHeader } from 'react-data-grid-addons';

const { DraggableContainer, DraggableHeaderCell } = DraggableHeader;

const columns = [
  { key: 'id', name: 'ID' },
  { key: 'name', name: 'Name' },
  { key: 'age', name: 'Age' },
];

const rows = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  // Add more rows here
];

const MyDataGrid = () => {
  const [gridColumns, setGridColumns] = React.useState(columns);
  const [gridRows, setGridRows] = React.useState(rows);

  const handleColumnReorder = (sourceIdx, targetIdx) => {
    const updatedColumns = [...gridColumns];
    const [columnToReorder] = updatedColumns.splice(sourceIdx, 1);
    updatedColumns.splice(targetIdx, 0, columnToReorder);
    setGridColumns(updatedColumns);
  };

  return (
    <ReactDataGrid
      columns={gridColumns}
      rows={gridRows}
      rowKey="id"
      headerRowHeight={50}
      headerCellRenderer={DraggableHeaderCell}
      draggableHeaderCell={DraggableContainer}
      onHeaderDrop={handleColumnReorder}
    />
  );
};

export default MyDataGrid;

Hope this helps.

Skerdi Velo
  • 121
  • 2
  • 13
  • have you also installed 'react-data-grid-addons'? I also installed that and receive multiple error like this: 'export 'DragItemTypes' (imported as 'DragItemTypes') was not found in 'react-data-grid'. – gdv Jul 25 '23 at 12:56