JJ36
JJ36

Reputation: 169

React collapse row onClick

I have data that I need to show in table, for all rows I would like to use collapse function. Now I have working code that is collapsing all rows on click, but in what way I can collapse only one already clicked?

This is my code:

class Data extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            datas: [
                {name: "or1", status: 11},
                {name: "or3", status: 2},
                {name: "or2", status: 22},
            ],
            expanded: [],
            isOpen: true,
        };
    }

    toogleContent(openIs) {
        this.setState({
            isOpen: !openIs
        })
    }

    render() {
        return (
            <Table responsive>
                <thead className="text-primary">
                <tr>
                    <th>Name</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                {this.state.datas.map((data, i) => (
                    <tr id={i} onClick={this.toogleContent.bind(this, this.state.isOpen)}>
                        <td>{data.name}</td>
                        <td><Collapse isOpen={this.state.isOpen}> 
                           {data.status}</Collapse>
                        </td>
                    </tr>
                ))}
                </tbody>
            </Table>
        )
    }
}

Upvotes: 1

Views: 1733

Answers (1)

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

I used their indexes to find out if they are opened or not, but you can use their names too, or add at data object a key isOpened =>

state={
    isOpenIndexes = []
}

toogleContent(index) {
    // we check if already opened
    this.state.isOpenIndexes.find(openedIndex => openedIndex ===index ) ? 
    this.setState({
        isOpenIndexes: this.state.isOpenIndexes.filter(openedIndex => openedIndex!==index)
    })
     :
    this.setState({
        isOpenIndexes: isOpenIndexes.concat([index])
    })
}

{datas.map((data, i) => (
                <tr id={i} onClick={this.toogleContent.bind(this, i)} isOpened={this.state.isOpenIndexes.find(openedIndex => openedIndex ===i )}>
                    <td>{data.name}</td>
                    <td>{data.status}</td>
                </tr>
            ))}

Upvotes: 1

Related Questions