reactjsmui-x-data-grid

Mui Datagrid new row on top


Using mui/x-data-grid I have a grid with a button to ad a new row. It works fin except that the new added row appears at the end of the grid, which is inconvenient if there are a lot of rows. How to make it appear on top?

Here is the code for the new row

    {
        // Create a new row object with a unique ID and default property values
        const newRow = { id: uuidv4(), reg_name: "", reg_created: '' };
        setRegions([...regions, newRow]);
    };

I also tried to revers it (setRegions([newRow, ...regions])) but it doen't help

enter image description here


Solution

  • Try to call unshift, and use the function version of useState.

    const [regions, setRegions] = useState([]);
    
    // ...
    
    setRegions((existingRegions) => {
      const updatedRegions = structuredClone(existingRegions);
      const newRow = { id: uuidv4(), reg_name: "", reg_created: '' };
      updatedRegions.unshift(newRow);
      return updatedRegions;
    });
    

    Also, it looks like the column is sorted by Name (descending). So you may need to add some custom sorting logic to the grid for new data or something.