0

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
    })
  }
1
  • The handleClick does not handle the toggle event. You're just pushing the current selected index to selected rows and you're not really setting activeIndex on the state. Commented Jan 20, 2020 at 15:56

1 Answer 1

1

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.