React Grid Search Filter

    The Ignite UI for React Search Filter feature in React Grid enables the process of finding values in the collection of data. We make it easier to set up this functionality and it can be implemented with a search input box, buttons, keyboard navigation and other useful features for an even better user experience. While browsers natively provide content search functionality, most of the time the IgrGrid virtualizes its columns and rows that are out of view. In these cases, the native browser search is unable to search data in the virtualized cells, since they are not part of the DOM. We have extended the React Material table-based grid with a search API that allows you to search through the virtualized content of the IgrGrid.

    React Search Example

    The following example represents IgrGrid with search input box that allows searching in all columns and rows, as well as specific filtering options for each column.

    React Search Usage

    Grid Setup

    Vamos começar criando nossa grade e vinculando-a aos nossos dados. Também adicionaremos alguns estilos personalizados para os componentes que usaremos!

    .gridSize {
        --ig-size: var(--ig-size-small);
    }
    
    <IgrGrid ref={gridRef} className="gridSize" autoGenerate="false" allowFiltering="true" data={data}>
        <IgrColumn field="IndustrySector" dataType="string" sortable="true"></IgrColumn>        
        <IgrColumn field="IndustryGroup" dataType="string" sortable="true"></IgrColumn>        
        <IgrColumn field="SectorType" dataType="string" sortable="true"></IgrColumn>        
        <IgrColumn field="KRD" dataType="number" sortable="true"></IgrColumn>        
        <IgrColumn field="MarketNotion" dataType="number" sortable="true"></IgrColumn>  
    </IgrGrid>
    

    Great, and now let's prepare for the search API of our IgrGrid! We can create a few properties, which can be used for storing the currently searched text and whether the search is case sensitive and/or by an exact match.

    const gridRef = useRef<IgrGrid>(null);
    const searchIconRef = useRef<IgrIconButton>(null)
    const clearIconRef = useRef<IgrIconButton>(null);
    const iconButtonPrevRef = useRef<IgrIconButton>(null);
    const caseSensitiveChipRef = useRef<IgrChip>(null);
    const exactMatchChipRef = useRef<IgrChip>(null);
    const iconButtonNextRef = useRef<IgrIconButton>(null);
    const [searchText, setSearchText] = useState('')
    

    React Search Box Input

    Now let's create our search input! By binding our searchText to the value property to our newly created input and subscribe to the inputOccured event, we can detect every single searchText modification by the user. This will allow us to use the IgrGrid's findNext and findPrev methods to highlight all the occurrences of the searchText and scroll to the next/previous one (depending on which method we have invoked).

    Ambos os métodos e findNext os findPrev métodos têm três argumentos:

    • Text: string (o texto que estamos procurando)
    • (opcional) CaseSensitive: boolean (a pesquisa deve diferenciar maiúsculas de minúsculas ou não, o valor padrão é false)
    • (opcional) ExactMatch: boolean (a busca deve ser por uma correspondência exata ou não, o valor padrão é false)

    Ao pesquisar por uma correspondência exata, a API de pesquisa destacará como resultados apenas os valores de células que correspondem inteiramente ao SearchText, levando em conta também a diferenciação entre maiúsculas e minúsculas. Por exemplo, as strings 'software' e 'Software' são uma correspondência exata, desconsiderando a diferenciação entre maiúsculas e minúsculas.

    The methods from above return a number value (the number of times the IgrGrid contains the given string).

    function handleOnSearchChange(input: IgrInput, event: IgrComponentValueChangedEventArgs) {
        setSearchText(event.detail);
        gridRef.current.findNext(event.detail, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    function nextSearch() {
        gridRef.current.findNext(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    
    <IgrInput name="searchBox" value={searchText} inputOcurred={handleOnSearchChange}>
    </IgrInput>
    

    Add Search Buttons

    Para pesquisar e navegar livremente entre nossos resultados de pesquisa, vamos criar alguns botões invocando o findNext e os findPrev métodos dentro dos respectivos manipuladores de eventos de clique dos botões.

    function prevSearch() {
        gridRef.current.findPrev(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    function nextSearch() {
        gridRef.current.findNext(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    <IgrIconButton key="prevIconButton" ref={iconButtonPrevRef} variant="flat" name="prev" collection="material" clicked={prevSearch}>
    </IgrIconButton>
    <IgrIconButton key="nextIconButton" ref={iconButtonNextRef} variant="flat" name="next" collection="material" clicked={nextSearch}>
    </IgrIconButton>
    

    We can also allow the users to navigate the results by using the keyboard's arrow keys and the Enter key. In order to achieve this, we can handle the keydown event of our search input by preventing the default caret movement of the input with the PreventDefault method and invoke the findNext/findPrev methods depending on which key the user has pressed.

    function searchKeyDown(e: KeyboardEvent<HTMLElement>) {
        if (e.key === 'Enter') {
            e.preventDefault();
            gridRef.current.findNext(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
        } else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
            e.preventDefault();
            gridRef.current.findPrev(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
        }
    }
    
     <div onKeyDown={searchKeyDown}>
        <IgrInput name="searchBox" value={searchText} inputOcurred={handleOnSearchChange}></IgrInput>
    </div>
    

    Case Sensitive and Exact Match

    Now let's allow the user to choose whether the search should be case sensitive and/or by an exact match. For this purpose we can use the IgrChip and get its reference and use the selected property.

    const caseSensitiveChipRef = useRef<IgrChip>(null);
    const exactMatchChipRef = useRef<IgrChip>(null);
    
    function updateSearch() {
        gridRef.current.findNext("searchValue", caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    <IgrChip ref={caseSensitiveChipRef} key="caseSensitiveChip" selectable="true">
        <span key="caseSensitive">Case Sensitive</span>
    </IgrChip>
    <IgrChip ref={exactMatchChipRef} key="exactMatchChip" selectable="true">
        <span key="exactMatch">Exact Match</span>
    </IgrChip>
    

    Persistence

    What if we would like to filter and sort our IgrGrid or even to add and remove records? After such operations, the highlights of our current search automatically update and persist over any text that matches the SearchText! Furthermore, the search will work with paging and will persist the highlights through changes of the IgrGrid's PerPage property.

    Adding icons

    Ao usar alguns dos nossos outros componentes, podemos criar uma interface de usuário enriquecida e melhorar o design geral de toda a nossa barra de pesquisa! Podemos ter um belo ícone de pesquisa ou exclusão à esquerda da entrada de pesquisa, alguns chips para nossas opções de pesquisa e alguns ícones de material design combinados com belos botões em estilo ripple para nossa navegação à direita. Podemos envolver esses componentes dentro de um grupo de entrada para um design mais refinado.

    import { IgrGridModule } from "igniteui-react-grids";
    import { IgrChipModule } from "igniteui-react";
    
    const mods: any[] = [IgrGridModule, IgrChipModule];
    mods.forEach((m) => m.register());
    

    Por fim, vamos atualizar nosso modelo com os novos componentes!

    const prevIconText =
      "<svg width='24' height='24' viewBox='0 0 24 24'><path d='M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z'></path></svg>";
    const nextIconText =
      "<svg width='24' height='24' viewBox='0 0 24 24'><path d='M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z'></path></svg>";
    const clearIconText =
      "<svg width='24' height='24' viewBox='0 0 24 24' title='Clear'><path d='M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'></path></svg>";
      const searchIconText =
      "<svg width='24' height='24' viewBox='0 0 24 24'><path d='M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z' /></svg>";
    
    useEffect(() => {
         if (searchIconRef?.current) {
          searchIconRef.current.registerIconFromText("search", searchIconText, "material");
          searchIconRef.current.registerIconFromText("clear", clearIconText, "material");
        }
        if (iconButtonPrevRef?.current) {
            iconButtonPrevRef.current.registerIconFromText("prev", prevIconText, "material");
        }
        if (iconButtonNextRef?.current) {
            iconButtonNextRef.current.registerIconFromText("next", nextIconText, "material");
        }
    }, []);
    
    <IgrInput name="searchBox" value={searchText} inputOcurred={handleOnSearchChange}>
        <div slot="prefix" key="prefix">
            {searchText.length === 0 ? (
                <IgrIconButton
                  key="searchIcon"
                  ref={searchIconRef} 
                  variant="flat"
                  name="search" 
                  collection="material"
                ></IgrIconButton>
                ) : (
                <IgrIconButton
                  key="clearIcon"
                  ref={clearIconRef}
                  variant="flat"
                  name="clear"
                  collection="material"
                  clicked={clearSearch}
                ></IgrIconButton>
            )}
        </div>
        <div slot="suffix" key="chipSuffix">
            <IgrChip ref={caseSensitiveChipRef} key="caseSensitiveChip" selectable="true">
            <span key="caseSensitive">Case Sensitive</span>
            </IgrChip>
            <IgrChip ref={exactMatchChipRef} key="exactMatchChip" selectable="true">
            <span key="exactMatch">Exact Match</span>
            </IgrChip>
        </div>
        <div slot="suffix" key="buttonsSuffix">
            <IgrIconButton key="prevIconButton" ref={iconButtonPrevRef} variant="flat" name="prev" collection="material" clicked={prevSearch}>
            </IgrIconButton>
            <IgrIconButton key="nextIconButton" ref={iconButtonNextRef} variant="flat" name="next" collection="material" clicked={nextSearch}>
            </IgrIconButton>
        </div>
    </IgrInput>
    

    À direita, em nosso grupo de entrada, vamos criar três contêineres separados com as seguintes finalidades:

    • Para exibir alguns chips que alternam as propriedades CaseSensitive e ExactMatch. Substituímos as caixas de seleção por dois chips estilosos que mudam de cor com base nessas propriedades. Sempre que um chip é clicado, invocamos seu respectivo manipulador.
    <div slot="suffix" key="chipSuffix">
        <IgrChip ref={caseSensitiveChipRef} key="caseSensitiveChip" selectable="true" select={handleCaseSensitiveChange}>
            <span key="caseSensitive">Case Sensitive</span>
        </IgrChip>
        <IgrChip ref={exactMatchChipRef} key="exactMatchChip" selectable="true" select={handleExactMatchChange}>
            <span key="exactMatch">Exact Match</span>
        </IgrChip>
    </div>
    
    function handleCaseSensitiveChange(chip: IgrChip, event: IgrComponentBoolValueChangedEventArgs) {
      gridRef.current.findNext(searchText, event.detail, exactMatchChipRef.current.selected);
    }
    function handleExactMatchChange(chip: IgrChip, event: IgrComponentBoolValueChangedEventArgs) {
      gridRef.current.findNext(searchText, caseSensitiveChipRef.current.selected, event.detail);
    }
    
    • Para os botões de navegação de pesquisa, transformamos nossas entradas em botões de estilo ondulado com ícones de materiais. Os manipuladores para os eventos de clique permanecem os mesmos - invocando os métodos / findNext​ ​findPrev.
    function prevSearch() {
        gridRef.current.findPrev(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    function nextSearch() {
        gridRef.current.findNext(searchText, caseSensitiveChipRef.current.selected, exactMatchChipRef.current.selected);
    }
    
    <div slot="suffix" key="buttonsSuffix">
        <IgrIconButton key="prevIconButton" ref={iconButtonPrevRef} variant="flat" name="prev" collection="material" clicked={prevSearch}>
        </IgrIconButton>
        <IgrIconButton key="nextIconButton" ref={iconButtonNextRef} variant="flat" name="next" collection="material" clicked={nextSearch}>
        </IgrIconButton>
    </div>
    

    Known Limitations

    Limitação Descrição
    Pesquisando em células com um modelo Os destaques da funcionalidade de pesquisa funcionam apenas para os modelos de célula padrão. Se você tiver uma coluna com modelo de célula personalizado, os destaques não funcionarão, então você deve usar abordagens alternativas, como um formatador de coluna, ou definir osearchable propriedade na coluna como falsa.
    Virtualização Remota A pesquisa não funcionará corretamente ao usar virtualização remota
    Células com texto cortado Quando o texto na célula é muito grande para caber e o texto que estamos procurando é cortado pelas reticências, ainda rolaremos até a célula e a incluiremos na contagem de correspondências, mas nada será destacado

    API References

    In this article we implemented our own search bar for the IgrGrid with some additional functionality when it comes to navigating between the search results. We also used some additional Ignite UI for React components like icons, chips and inputs. The search API is listed below.

    IgrGrid methods:

    IgrColumn properties:

    Componentes adicionais com APIs relativas que foram usadas:

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.