-
Notifications
You must be signed in to change notification settings - Fork 860
[EuiDataGrid] Add renderCustomGridBody API
#6624
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
6948fc0
[Setup] Split up `RowHeightUtils` into virtualized/non-virtualized cl…
cee-chen 045fd11
Add `RowHeightUtilsType` + update downstream type references
cee-chen ca74ca9
Update `RowHeightUtils` test mocks
cee-chen b8c231b
[optional tech debt] Convert row heights tests to RTL `renderHook`
cee-chen b6aab71
[Setup] Add `renderCustomGridBody` API to top-level data grid
cee-chen ea30216
Add documentation example
cee-chen e787cdc
[EuiDataGridBody] Split up into custom and virtualized body renderers
cee-chen 6dc960b
Set up header & footer render
cee-chen f3b33a2
DRY out shared `Cell` wrapper component
cee-chen 9f548e3
Write tests for custom renderer
cee-chen 8095cfb
Fix incredibly bizarre rerender/unmount bug
cee-chen 105290a
Fix various row/cell-related CSS
cee-chen 9f40db4
[misc] Remove unnecessary `top: 0` from non-virtualized cells
cee-chen fea3601
changelog
cee-chen e8e9b57
Improve copy on props docs
cee-chen 2a2d8e8
Fix failing Cypress test
cee-chen c69e4d6
[PR feedback] Add new `setCustomGridBodyProps` callback param to `ren…
cee-chen c1d280f
Add explicit ref typing + tests
cee-chen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
285 changes: 285 additions & 0 deletions
285
src-docs/src/views/datagrid/advanced/custom_renderer.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,285 @@ | ||
| import React, { useEffect, useCallback, useState } from 'react'; | ||
| import { css } from '@emotion/react'; | ||
| import { faker } from '@faker-js/faker'; | ||
|
|
||
| import { | ||
| EuiDataGrid, | ||
| EuiDataGridProps, | ||
| EuiDataGridCustomBodyProps, | ||
| EuiDataGridColumnCellActionProps, | ||
| EuiScreenReaderOnly, | ||
| EuiCheckbox, | ||
| EuiButtonIcon, | ||
| EuiIcon, | ||
| EuiFlexGroup, | ||
| EuiSwitch, | ||
| EuiSpacer, | ||
| useEuiTheme, | ||
| logicalCSS, | ||
| } from '../../../../../src'; | ||
|
|
||
| const raw_data: Array<{ [key: string]: string }> = []; | ||
| for (let i = 1; i < 100; i++) { | ||
| raw_data.push({ | ||
| name: `${faker.name.lastName()}, ${faker.name.firstName()}`, | ||
| email: faker.internet.email(), | ||
| location: `${faker.address.city()}, ${faker.address.country()}`, | ||
| date: `${faker.date.past()}`, | ||
| amount: faker.commerce.price(1, 1000, 2, '$'), | ||
| }); | ||
| } | ||
|
|
||
| const columns = [ | ||
| { | ||
| id: 'name', | ||
| displayAsText: 'Name', | ||
| cellActions: [ | ||
| ({ Component }: EuiDataGridColumnCellActionProps) => ( | ||
| <Component | ||
| onClick={() => alert('action')} | ||
| iconType="faceHappy" | ||
| aria-label="Some action" | ||
| > | ||
| Some action | ||
| </Component> | ||
| ), | ||
| ], | ||
| }, | ||
| { | ||
| id: 'email', | ||
| displayAsText: 'Email address', | ||
| initialWidth: 130, | ||
| }, | ||
| { | ||
| id: 'location', | ||
| displayAsText: 'Location', | ||
| }, | ||
| { | ||
| id: 'date', | ||
| displayAsText: 'Date', | ||
| }, | ||
| { | ||
| id: 'amount', | ||
| displayAsText: 'Amount', | ||
| }, | ||
| ]; | ||
|
|
||
| const leadingControlColumns: EuiDataGridProps['leadingControlColumns'] = [ | ||
| { | ||
| id: 'selection', | ||
| width: 32, | ||
| headerCellRender: () => ( | ||
| <EuiCheckbox | ||
| id="select-all-rows" | ||
| aria-label="Select all rows" | ||
| onChange={() => {}} | ||
| /> | ||
| ), | ||
| rowCellRender: ({ rowIndex }) => ( | ||
| <EuiCheckbox | ||
| id={`select-row-${rowIndex}`} | ||
| aria-label="Select row" | ||
| onChange={() => {}} | ||
| /> | ||
| ), | ||
| }, | ||
| ]; | ||
|
|
||
| const trailingControlColumns: EuiDataGridProps['trailingControlColumns'] = [ | ||
| { | ||
| id: 'actions', | ||
| width: 40, | ||
| headerCellRender: () => ( | ||
| <EuiScreenReaderOnly> | ||
| <span>Actions</span> | ||
| </EuiScreenReaderOnly> | ||
| ), | ||
| rowCellRender: () => ( | ||
| <EuiButtonIcon iconType="boxesHorizontal" aria-label="See row actions" /> | ||
| ), | ||
| }, | ||
| ]; | ||
|
|
||
| // The custom row details is actually a trailing control column cell with | ||
| // a hidden header. This is important for accessibility and markup reasons | ||
| // @see https://fuschia-stretch.glitch.me/ for more | ||
| const rowDetails: EuiDataGridProps['trailingControlColumns'] = [ | ||
| { | ||
| id: 'row-details', | ||
|
|
||
| // The header cell should be visually hidden, but available to screen readers | ||
| width: 0, | ||
| headerCellRender: () => <>Row details</>, | ||
| headerCellProps: { className: 'euiScreenReaderOnly' }, | ||
|
|
||
| // The footer cell can be hidden to both visual & SR users, as it does not contain meaningful information | ||
| footerCellProps: { style: { display: 'none' } }, | ||
|
|
||
| // When rendering this custom cell, we'll want to override | ||
| // the automatic width/heights calculated by EuiDataGrid | ||
| rowCellRender: ({ setCellProps, rowIndex }) => { | ||
| setCellProps({ style: { width: '100%', height: 'auto' } }); | ||
|
|
||
| const firstName = raw_data[rowIndex].name.split(', ')[1]; | ||
| const isGood = faker.datatype.boolean(); | ||
| return ( | ||
| <> | ||
| {firstName}'s account has {isGood ? 'no' : ''} outstanding fees.{' '} | ||
| <EuiIcon | ||
| type={isGood ? 'checkInCircleFilled' : 'error'} | ||
| color={isGood ? 'success' : 'danger'} | ||
| /> | ||
| </> | ||
| ); | ||
| }, | ||
| }, | ||
| ]; | ||
|
|
||
| const footerCellValues: { [key: string]: string } = { | ||
| amount: `Total: ${raw_data | ||
| .reduce((acc, { amount }) => acc + Number(amount.split('$')[1]), 0) | ||
| .toLocaleString('en-US', { style: 'currency', currency: 'USD' })}`, | ||
| }; | ||
|
|
||
| const RenderFooterCellValue: EuiDataGridProps['renderFooterCellValue'] = ({ | ||
| columnId, | ||
| setCellProps, | ||
| }) => { | ||
| const value = footerCellValues[columnId]; | ||
|
|
||
| useEffect(() => { | ||
| // Turn off the cell expansion button if the footer cell is empty | ||
| if (!value) setCellProps({ isExpandable: false }); | ||
| }, [value, setCellProps, columnId]); | ||
|
|
||
| return value || null; | ||
| }; | ||
|
|
||
| export default () => { | ||
| const [autoHeight, setAutoHeight] = useState(true); | ||
| const [showRowDetails, setShowRowDetails] = useState(false); | ||
|
|
||
| // Column visibility | ||
| const [visibleColumns, setVisibleColumns] = useState(() => | ||
| columns.map(({ id }) => id) | ||
| ); | ||
|
|
||
| // Pagination | ||
| const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 }); | ||
| const onChangePage = useCallback((pageIndex) => { | ||
| setPagination((pagination) => ({ ...pagination, pageIndex })); | ||
| }, []); | ||
| const onChangePageSize = useCallback((pageSize) => { | ||
| setPagination((pagination) => ({ ...pagination, pageSize })); | ||
| }, []); | ||
|
|
||
| // Sorting | ||
| const [sortingColumns, setSortingColumns] = useState([]); | ||
| const onSort = useCallback((sortingColumns) => { | ||
| setSortingColumns(sortingColumns); | ||
| }, []); | ||
|
|
||
| const { euiTheme } = useEuiTheme(); | ||
|
|
||
| // Custom grid body renderer | ||
| const RenderCustomGridBody = useCallback( | ||
| ({ Cell, visibleColumns, visibleRowData }: EuiDataGridCustomBodyProps) => { | ||
| const visibleRows = raw_data.slice( | ||
| visibleRowData.startRow, | ||
| visibleRowData.endRow | ||
| ); | ||
|
|
||
| const styles = { | ||
| row: css` | ||
| ${logicalCSS('width', 'fit-content')}; | ||
| ${logicalCSS('border-bottom', euiTheme.border.thin)}; | ||
| background-color: ${euiTheme.colors.emptyShade}; | ||
| `, | ||
| rowCellsWrapper: css` | ||
| display: flex; | ||
| `, | ||
| rowDetailsWrapper: css` | ||
| text-align: center; | ||
| background-color: ${euiTheme.colors.body}; | ||
| `, | ||
| }; | ||
|
|
||
| return ( | ||
| <> | ||
| {visibleRows.map((row, rowIndex) => ( | ||
| <div role="row" css={styles.row} key={rowIndex}> | ||
| <div css={styles.rowCellsWrapper}> | ||
| {visibleColumns.map((column, colIndex) => { | ||
| // Skip the row details cell - we'll render it manually outside of the flex wrapper | ||
| if (column.id !== 'row-details') { | ||
| return ( | ||
| <Cell | ||
| colIndex={colIndex} | ||
| visibleRowIndex={rowIndex} | ||
| key={`${rowIndex},${colIndex}`} | ||
| /> | ||
| ); | ||
| } | ||
| })} | ||
| </div> | ||
| {showRowDetails && ( | ||
| <div css={styles.rowDetailsWrapper}> | ||
| <Cell | ||
| colIndex={visibleColumns.length - 1} // If the row is being shown, it should always be the last index | ||
| visibleRowIndex={rowIndex} | ||
| /> | ||
| </div> | ||
| )} | ||
| </div> | ||
| ))} | ||
| </> | ||
| ); | ||
| }, | ||
| [showRowDetails, euiTheme] | ||
| ); | ||
|
|
||
| return ( | ||
| <> | ||
| <EuiFlexGroup alignItems="center"> | ||
| <EuiSwitch | ||
| label="Set static grid height" | ||
| checked={!autoHeight} | ||
| onChange={() => setAutoHeight(!autoHeight)} | ||
| /> | ||
| <EuiSwitch | ||
| label="Toggle custom row details" | ||
| checked={showRowDetails} | ||
| onChange={() => setShowRowDetails(!showRowDetails)} | ||
| /> | ||
| </EuiFlexGroup> | ||
| <EuiSpacer /> | ||
| <EuiDataGrid | ||
| aria-label="Data grid custom body renderer demo" | ||
| columns={columns} | ||
| leadingControlColumns={leadingControlColumns} | ||
| trailingControlColumns={ | ||
| showRowDetails | ||
| ? [...trailingControlColumns, ...rowDetails] | ||
| : trailingControlColumns | ||
| } | ||
| columnVisibility={{ visibleColumns, setVisibleColumns }} | ||
| sorting={{ columns: sortingColumns, onSort }} | ||
| inMemory={{ level: 'sorting' }} | ||
| pagination={{ | ||
| ...pagination, | ||
| pageSizeOptions: [10, 25, 50], | ||
| onChangePage: onChangePage, | ||
| onChangeItemsPerPage: onChangePageSize, | ||
| }} | ||
| rowCount={raw_data.length} | ||
| renderCellValue={({ rowIndex, columnId }) => | ||
| raw_data[rowIndex][columnId] | ||
| } | ||
| renderFooterCellValue={RenderFooterCellValue} | ||
| renderCustomGridBody={RenderCustomGridBody} | ||
| height={autoHeight ? undefined : 400} | ||
| gridStyle={{ border: 'none', header: 'underline' }} | ||
| /> | ||
| </> | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
TIL, thank you 👍