How to collapse other expanded rows in react-table

lletgo picture lletgo · Nov 6, 2017 · Viewed 17.1k times · Source

I am using React Table in my project, I don't know how to close other expanded rows when user clicks one expanded, i.e. when first, second, and third rows are all expanded, I want to close all of the three when user click the fourth row.

Can someone tell me how?

Answer

Arnaud Enesvat picture Arnaud Enesvat · Nov 11, 2017

For anyone looking for more info about that :

//in component constructor, add state declaration :

this.state = {
    expanded: {}
}

//in component render function - set "expanded" to component state:

expanded={this.state.expanded}

// still in component render() - set an event callback - I prefer to use a dedicated event manager here named handleRowExpanded :

onExpandedChange={(newExpanded, index, event) => this.handleRowExpanded(newExpanded, index, event)}

// then declare an event manager :

   handleRowExpanded(newExpanded, index, event) {
        this.setState({
        // we override newExpanded, keeping only current selected row expanded
            expanded: {[index]: true}
        });
    }

HTH :)