bulkreact-admin

react-admin: Access <List/> records from bulkActions


The docs state that bulkActions don't get selected records of a List component, just the selected ids, but i need to check a specific field in each selected record from a button's click handler of the bulkActionsButtons.

Any ideas of how this could be achieved?


Solution

  • Ok, this is what i did and it works. A combination of a render prop and a ref. Please if anyone have a better idea, please let me now.

    import React, {Component} from 'react';
    import {
        List,
        Datagrid,
        TextField,
        Button
    } from 'react-admin';
    
    class MyBulkButtons extends Component {
        handleClick = () => {
            const {getSelectedRecords} = this.props;
            const records = getSelectedRecords();
            const selectedRecords = records.filter(i => i.title === 'Extra action!');
    
            this.processExtraActions(selectedRecords);
        };
    
        processExtraActions(selectedRecords) {
            //...
        }
    
        render() {
            return (
              <Button onClick={this.handleClick} label={"Check for extra actions"}/>
            );
        }
    }
    
    export class MyList extends Component {
        constructor(props) {
            super(props);
            this.myDataGrid = React.createRef();
        }
    
        getSelectedRecords() {
            const gridProps = this.myDataGrid.current.props;
    
            return gridProps.selectedIds.map(id => gridProps.data[id]);
        }
    
        render() {
            return (
              <List {...this.props}
                    bulkActionButtons={<MyBulkButtons getSelectedRecords={this.getSelectedRecords.bind(this)}/>}>
    
                  <Datagrid ref={this.myDataGrid}>
                      <TextField source="id"/>
                      <TextField source="title"/>
                  </Datagrid>
              </List>
            );
        }
    }