Raja O
Raja O

Reputation: 644

Table Row Update/Remove Data in State(Array) and Toggle Add/Remove Class in React

I'm having list of table and each row is clickable. Once I onclick the row need to add corresponding data to array. If I again click the same row need to remove the data from array. Likewise i need to add an toggle Active class for selected row.

const data = [
    {
        name: "Name1",
        foramt: "pdf",
        version: 0
    },
    {
        name: "Name2",
        foramt: "pdf",
        version: 0
    },
    {
        name: "Name3",
        foramt: "pdf",
        version: 2
    },
    {
        name: "Name4",
        foramt: "pdf",
        version: 5
    },
]
this.state = {
    active: false,
    activeIndex: null,
    selectedRow: []
}

<Table>
    data.map((item, index) => {
        const rowSelected = this.state.activeIndex === index ? "row-selected" : "";
     return 
        <TableRow className = {rowSelected} onClick={this.handleClick(item,index)}>
            <Cell>{item.name}</Cell>
            <Cell>{item.format}</Cell>
        </TableRow>
    })
</Table>

 handleClick = (item,index) => {
     const {activeIndex} = this.state;
     let array = []
    if(activeIndex !== index) {
        array.push(item);
    }
    this.setState({
      selectedRows: array
    })
  }

Upvotes: 0

Views: 418

Answers (1)

evolon
evolon

Reputation: 1586

For the TableRow onCLick event:

Change this:

onClick={this.handleClick(item,index)}

To

onClick={() => this.handleClick(item, index)}

The first case will run immediately instead of waiting for the event to be called.

And for the className

Change this:

className={rowSelected}

To:

className={rowSelected ? "row-selected" : null}

In the first one when the rowSelected === true you'd get className={true} which doesn't really point to any class name. In the second example though you'd get className="selected"

Upvotes: 1

Related Questions