UNPKG

@carbon/react

Version:

React components for the Carbon Design System

55 lines (51 loc) 1.85 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { initialSortState, getSortedState } from './sorting.js'; import normalize from '../tools/normalize.js'; /** * Helper to derive the next state from the given props and the * prevState. Potential future-facing API hook for React v17. * * Currently, it's being used as a way to normalize the incoming data that we * are receiving for rows */ const getDerivedStateFromProps = (props, prevState) => { const { rowIds, rowsById, cellsById } = normalize(props.rows, props.headers, prevState); const state = { rowIds, rowsById, cellsById, sortDirection: prevState.sortDirection || initialSortState, sortHeaderKey: prevState.sortHeaderKey || null, // Copy over rowIds so the reference doesn't mutate the stored // `initialRowOrder` initialRowOrder: rowIds.slice(), filterInputValue: prevState.filterInputValue || null, // Optional state field to indicate whether a consumer should show a // batch actions menu shouldShowBatchActions: prevState.shouldShowBatchActions || false, // TODO: Investigate deleting this property when this util is ported to // TypeScript. The only reason it was added was to address a type error in // packages/react/src/components/DataTable/DataTable.tsx isExpandedAll: false }; if (prevState.sortDirection && prevState.sortHeaderKey) { const { rowIds } = getSortedState(props, state, prevState.sortHeaderKey, prevState.sortDirection); state.rowIds = rowIds; } state.isExpandedAll = state.rowIds.every(id => { return state.rowsById[id].isExpanded === true; }); return state; }; export { getDerivedStateFromProps as default };