Skip to main content Skip to footer

Setting Default Values for Newly Added Rows in React

Default values being added to rows

Background:

By default, when you add a new row to a data grid like FlexGrid, the new row is empty. Often developers want newly added rows to come pre-populated with default values. FlexGrid makes this easy by using the newItemCreator property of its CollectionView, which allows you to specify a function that returns the default values for each newly created item.

Steps to Complete:

  1. Create a CollectionView and assign it as the grid’s itemsSource.
  2. Use newItemCreator on the CollectionView to define default values for newly added rows.

Getting Started:

Create a CollectionView and assign it as the grid’s itemsSource

A CollectionView wraps your data and provides hooks such as newItemCreator. Setting allowAddNew to true enables the grid’s built-in new-row template so users can add rows through the UI.

import * as wjcCore from '@mescius/wijmo';
import { FlexGrid } from '@mescius/wijmo.react.grid';

const items = new wjcCore.CollectionView(getData(10), {
  newItemCreator: () => ({
    id: getUniqueId(),
    country: 'Default Country',
    discount: 0,
    downloads: 0,
    sales: 0,
    expenses: 0
  })
});
<FlexGrid
  itemsSource={items}
  allowAddNew={true}
/>
  • When the user begins editing the new-row template, FlexGrid calls newItemCreator to generate the default row values.

 

Use newItemCreator on the CollectionView to define default values for newly added rows

The newItemCreator function returns a plain object that becomes the data for the new row. These values appear immediately when the row is created.

function getUniqueId() {
  const arr = items.sourceCollection;
  return Math.max(0, ...arr.map(item => item.id)) + 1;
}

 

Code for Reference

import { useMemo } from 'react';
import * as wjcCore from '@mescius/wijmo';
import { FlexGrid } from '@mescius/wijmo.react.grid';

export default function App() {
  const items = useMemo(() => {
    return new wjcCore.CollectionView(getData(10), {
      newItemCreator: () => ({
        id: getNextId(),
        country: 'Default Country',
        discount: 0,
        downloads: 0,
        sales: 0,
        expenses: 0
      })
    });
  }, []);

  function getNextId() {
    const arr = items.sourceCollection;
    return Math.max(0, ...arr.map(i => i.id)) + 1;
  }

  return (
    <FlexGrid
      itemsSource={items}
      allowAddNew={true}
    />
  );
}

function getData(count: number) {
  return Array.from({ length: count }, (_, i) => ({
    id: i + 1,
    country: 'Country ' + (i + 1),
    discount: 0,
    downloads: 0,
    sales: 0,
    expenses: 0
  }));
}

 

With this React setup, any newly added row, whether added through the UI or programmatically, will be initialized with your predefined default values. This improves usability and ensures consistent data entry.

Happy coding!

Andrew Peterson

Technical Engagement Engineer