React Grid 검색 필터
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
그리드를 생성하고 이를 데이터에 바인딩하는 것부터 시작해 보겠습니다. 또한 우리가 사용할 구성 요소에 대한 몇 가지 사용자 정의 스타일을 추가할 것입니다!
.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 [caseSensitiveSelected, setCaseSensitiveSelected] = useState<boolean>(false);
const [exactMatchSelected, setExactMatchSelected] = useState<boolean>(false);
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).
Both the findNext and the findPrev methods have three arguments:
Text: string (the text we are searching for)- (optional)
CaseSensitive: boolean (should the search be case sensitive or not, default value is false) - (optional)
ExactMatch: boolean (should the search be by an exact match or not, default value is false)
When searching by an exact match, the search API will highlight as results only the cell values that match entirely the SearchText by taking the case sensitivity into account as well. For example the strings 'software' and 'Software' are an exact match with a disregard for the case sensitivity.
The methods from above return a number value (the number of times the IgrGrid contains the given string).
const handleOnSearchChange = (event: IgrComponentValueChangedEventArgs) => {
setSearchText(event.detail);
nextSearch(event.detail, caseSensitiveSelected, exactMatchSelected);
}
<IgrInput name="searchBox" value={searchText} onInput={handleOnSearchChange}>
</IgrInput>
Add Search Buttons
In order to freely search and navigate among our search results, let's create a couple of buttons by invoking the findNext and the findPrev methods inside the buttons' respective click event handlers.
const prevSearch = (text: string, caseSensitive: boolean, exactMatch: boolean) => {
gridRef.current.findPrev(text, caseSensitive, exactMatch);
}
const nextSearch = (text: string, caseSensitive: boolean, exactMatch: boolean) => {
gridRef.current.findNext(text, caseSensitive, exactMatch);
}
<IgrIconButton variant="flat" name="prev" collection="material" onClick={() => prevSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
</IgrIconButton>
<IgrIconButton variant="flat" name="next" collection="material" onClick={() => nextSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
</IgrIconButton>
Add Keyboard Search
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.
const searchKeyDown = (e: KeyboardEvent<HTMLElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
nextSearch(searchText, caseSensitiveSelected, exactMatchSelected);
} else if (e.key === 'ArrowUp' || e.key === 'ArrowLeft') {
e.preventDefault();
prevSearch(searchText, caseSensitiveSelected, exactMatchSelected);
}
}
<div onKeyDown={searchKeyDown}>
<IgrInput name="searchBox" value={searchText} onInput={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 component along with a boolean state variable to indicate whether the IgrChip is selected.
const [caseSensitiveSelected, setCaseSensitiveSelected] = useState<boolean>(false);
const [exactMatchSelected, setExactMatchSelected] = useState<boolean>(false);
const handleCaseSensitiveChange = (event: IgrComponentBoolValueChangedEventArgs) => {
setCaseSensitiveSelected(event.detail);
nextSearch(searchText, event.detail, exactMatchSelected);
}
const handleExactMatchChange = (event: IgrComponentBoolValueChangedEventArgs) => {
setExactMatchSelected(event.detail);
nextSearch(searchText, caseSensitiveSelected, event.detail);
}
<IgrChip selectable={true} onSelect={handleCaseSensitiveChange}>
<span>Case Sensitive</span>
</IgrChip>
<IgrChip selectable={true} onSelect={handleExactMatchChange}>
<span>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
다른 구성 요소 중 일부를 사용하여 풍부한 사용자 인터페이스를 만들고 전체 검색 창의 전반적인 디자인을 개선할 수 있습니다! 검색 입력 왼쪽에 멋진 검색 또는 삭제 아이콘, 검색 옵션을 위한 몇 개의 칩, 오른쪽 탐색을 위한 멋진 리플 스타일 버튼과 결합된 일부 재료 디자인 아이콘을 가질 수 있습니다.
Let's begin by creating the search navigation buttons on the right of the input by adding two ripple styled buttons with material icons. The handlers for the click events remain the same - invoking the findNext/findPrev methods.
- For displaying a couple of chips that toggle the
CaseSensitiveand theExactMatchproperties. We have replaced the checkboxes with two stylish chips. Whenever a chip is clicked, we invoke its respective handler.
const prevSearch = (text: string, caseSensitive: boolean, exactMatch: boolean) => {
gridRef.current.findPrev(text, caseSensitive, exactMatch);
}
const nextSearch = (text: string, caseSensitive: boolean, exactMatch: boolean) => {
gridRef.current.findNext(text, caseSensitive, exactMatch);
}
<div slot="suffix">
<IgrIconButton variant="flat" name="prev" collection="material" onClick={() => prevSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
<IgrRipple></IgrRipple>
</IgrIconButton>
<IgrIconButton variant="flat" name="next" collection="material" onClick={() => nextSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
<IgrRipple></IgrRipple>
</IgrIconButton>
</div>
이제 입력 왼쪽에 검색 및 지우기 아이콘을 추가해 보겠습니다.
const clearSearch = () => {
setSearchText('');
gridRef.current.clearSearch();
}
<div slot="prefix">
{searchText.length === 0 ? (
<IgrIconButton variant="flat" name="search" collection="material">
</IgrIconButton>
) : (
<IgrIconButton variant="flat" name="clear" collection="material" onClick={clearSearch}>
</IgrIconButton>
)}
</div>
마지막으로, 이것은 모든 것을 결합할 때의 최종 결과입니다.
useEffect(() => {
registerIconFromText("search", searchIconText, "material");
registerIconFromText("clear", clearIconText, "material");
registerIconFromText("prev", prevIconText, "material");
registerIconFromText("next", nextIconText, "material");
}, []);
<IgrInput name="searchBox" value={searchText} onInput={handleOnSearchChange}>
<div slot="prefix">
{searchText.length === 0 ? (
<IgrIconButton variant="flat" name="search" collection="material">
</IgrIconButton>
) : (
<IgrIconButton variant="flat" name="clear" collection="material" onClick={clearSearch}>
</IgrIconButton>
)}
</div>
<div slot="suffix">
<IgrIconButton variant="flat" name="prev" collection="material" onClick={() => prevSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
<IgrRipple></IgrRipple>
</IgrIconButton>
<IgrIconButton variant="flat" name="next" collection="material" onClick={() => nextSearch(searchText, caseSensitiveSelected, exactMatchSelected)}>
<IgrRipple></IgrRipple>
</IgrIconButton>
</div>
</IgrInput>
Known Limitations
| 한정 | 설명 |
|---|---|
| 템플릿을 사용하여 셀에서 검색 | 검색 기능 강조 표시는 기본 셀 템플릿에서만 작동합니다. 사용자 정의 셀 템플릿이 포함된 열이 있는 경우 강조 표시가 작동하지 않으므로 열 포맷터와 같은 대체 접근 방식을 사용하거나searchable 열의 속성을 false로 설정합니다. |
| 원격 가상화 | 원격 가상화를 사용하면 검색이 제대로 작동하지 않습니다. |
| 텍스트가 잘린 셀 | 셀의 텍스트가 너무 커서 맞지 않고 찾고 있는 텍스트가 줄임표로 잘려도 셀로 스크롤하여 일치 횟수에 포함시키지만 아무것도 강조 표시되지 않습니다. |
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:
사용된 관련 API가 포함된 추가 구성요소:
Additional Resources
우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.