React Grid Selection Overview

    With the Ignite UI for React Select feature in React Grid you can easily interact with and manipulate data using simple mouse interactions. There are three selection modes available:

    • Seleção de linha
    • Seleção de células
    • Column selection

    With the rowSelection property, you can specify:

    • Nenhum
    • Solteiro
    • Seleção múltipla

    React Grid Selection Example

    The sample below demonstrates three types of cell selection behaviors in the IgrGrid. Use the buttons below to enable each of the available selection modes.

    React Grid Selection Options

    The Ignite UI for React IgrGrid component provides three different selection modes - Row selection, Cell selection and Column selection. By default only Multi-cell selection mode is enabled in the IgrGrid. In order to change/enable selection mode you can use rowSelection, cellSelection or selectable properties.

    React Grid Row Selection

    permite rowSelection que você especifique as seguintes opções:

    • None - Row selection would be disabled for the IgrGrid.
    • Single - Selection of only one row within the IgrGrid would be available.
    • Multiple- A seleção de várias linhas estaria disponível usando os seletores de linha, com uma combinação de teclas como ctrl + clique, ou pressionando a tecla de espaço quando uma célula estiver em foco.

    Vá para o tópico Seleção de linha para obter mais informações.

    React Grid Cell Selection

    permite cellSelection que você especifique as seguintes opções:

    • None - Cell selection would be disabled for the IgrGrid.
    • Single - Selection of only one cell within the IgrGrid would be available.
    • Multiple - Currently, this is the default state of the selection in the IgrGrid. Multi-cell selection is available by mouse dragging over the cells, after a left button mouse clicked continuously.

    Vá para o tópico Seleção de célula para obter mais informações.

    React Grid Column Selection

    The selectable property enables you to specify the following options for each IgrColumn. The corresponding column selection will be enabled or disabled if this property is set to true or false, respectively.

    Isso leva às três variações seguintes:

    • Seleção única -mouse click sobre a célula da coluna.
    • Seleção de várias colunas - segurando ctrl + mouse click sobre as células da coluna.
    • Seleção de coluna de intervalo - segurando shift + mouse click seleciona tudo no meio.

    Acesse o tópico Seleção de coluna para obter mais informações.

    React Grid Context Menu

    Using the ContextMenu event you can add a custom context menu to facilitate your work with IgrGrid. With a right click on the grid's body, the event emits the cell on which it is triggered. The context menu will operate with the emitted cell.

    Se houver uma seleção de várias células, colocaremos lógica, que verificará se a célula selecionada está na área da seleção de várias células. Se for, também emitiremos os valores das células selecionadas.

    Basicamente, a função principal ficará assim:

    function rightClick(grid: IgrGridBaseDirective, event: IgrGridCellEventArgs) {
        const eventArgs = event.detail;
        eventArgs.event.preventDefault();
        const node = eventArgs.cell.id;
        const isCellWithinRange = grid.getSelectedRanges().some((range: any) => {
            if (node.columnID >= range.columnStart &&
                node.columnID <= range.columnEnd &&
                node.rowIndex >= range.rowStart &&
                node.rowIndex <= range.rowEnd
                ) {
                    return true;
                }
            return false;
        });
        setIsCellWithinRange(isCellWithinRange);
        setClickedCell(eventArgs.cell);
        openContextMenu(eventArgs.event.clientX, eventArgs.event.clientY)
    }
    

    O menu de contexto terá as seguintes funções:

    • Copie o valor da célula selecionada.
    • Copie o dataRow da célula selecionada.
    • Se a célula selecionada estiver dentro de um intervalo de seleção de várias células, copie todos os dados selecionados.
    function copySelectedRowData() {
        const selectedData = gridRef.current.getRowData(clickedCell.id.rowID);
        copyData(selectedData);
        closeContextMenu();
    }
    
    function copySelectedCellData() {
        const selectedData = clickedCell.value;
        copyData(selectedData);
        closeContextMenu();
    }
    
    function copySelectedData() {
        const selectedData = gridRef.current.getSelectedData(null,null);
        copyData(selectedData);
        closeContextMenu();
    }
    
    function copyData(data: any[]) {
        const tempElement = document.createElement('input');
        document.body.appendChild(tempElement);
        tempElement.setAttribute('id', 'temp_id');
        (document.getElementById('temp_id') as HTMLInputElement).value = JSON.stringify(data);
        tempElement.select();
        document.execCommand('copy');
        document.body.removeChild(tempElement);
        setSelectedData(JSON.stringify(data));
    }
    

    The IgrGrid will fetch the copied data and will paste it in a container element.

    O modelo que vamos usar para combinar a grade com o menu de contexto:

     <>
        <div className="container sample">
            <div className="wrapper" onClick={closeContextMenu}>
                <IgrGrid
                    autoGenerate="false"
                    data={northWindData}
                    primaryKey="ProductID"
                    ref={gridRef}
                    contextMenu={rightClick}>
                <IgrColumn field="ProductID" header="Product ID">
                </IgrColumn>
                <IgrColumn field="ProductName" header="Product Name">
                </IgrColumn>
                <IgrColumn field="UnitsInStock" header="Units In Stock" dataType="number">
                </IgrColumn>
                <IgrColumn field="UnitPrice" header="Units Price" dataType="number">
                </IgrColumn>
                <IgrColumn field="Discontinued" dataType="boolean">
                </IgrColumn>
                <IgrColumn field="OrderDate" header="Order Date" dataType="date">
                </IgrColumn>
                </IgrGrid>
                <div className="selected-data-area">
                    {selectedData}
                </div>
            </div>
        </div>
        <div style={{display: "none"}} className="contextmenu" ref={contextMenuRef}>
            <span className="item" onClick={copySelectedCellData}>
                <IgrIcon ref={iconRef} collection='material' name="content_copy"></IgrIcon>Copy Cell Data
            </span>
            <span className="item" onClick={copySelectedRowData}>
                <IgrIcon collection='material' name="content_copy"></IgrIcon>Copy Row Data
            </span>
            {isCellWithinRange && (
            <span className="item" onClick={copySelectedData}>
                <IgrIcon collection='material' name="content_copy"></IgrIcon>Copy Cells Data
            </span>)}
        </div>
    </>
    

    Selecione várias células e pressione o botão direito do mouse. O menu de contexto aparecerá e após selecionar Copy cells data os dados selecionados aparecerão na caixa vazia à direita.

    O resultado é:

    Known Issues and Limitations

    When the grid has no primaryKey set and remote data scenarios are enabled (when paging, sorting, filtering, scrolling trigger requests to a remote server to retrieve the data to be displayed in the grid), a row will lose the following state after a data request completes:

    • Seleção de linha
    • Expandir/recolher linha
    • Edição de linha
    • Fixação de linha

    API References

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.